I am trying to split number string to two to digit numbers

How do I get two different Numbers out that string


I want separate two numbers

x <- c("-26755.22-50150.60") 

To this


I have tried stringr::str_split but I din't manage to keep the digits.

  • $\begingroup$ I am using R for this $\endgroup$
    – Viz
    Mar 12, 2018 at 9:56
  • $\begingroup$ Do you have any delimiter? and the values are going to be like only 2 values after decimal right? $\endgroup$
    – Toros91
    Mar 12, 2018 at 9:59
  • $\begingroup$ There is no delimiter. I know that after 2 digits i have to separate these numbers. $\endgroup$
    – Viz
    Mar 12, 2018 at 10:04

2 Answers 2


I think this should do the thing for you:

#the input
str <- " -26755.22-50150.60"    

#you can use this command to split the data into 2 columns
#this doesn't have any constraint in the number of digits before and after the decimal
strspl <- as.numeric(unlist(regmatches(str,gregexpr("(?>-)*[[:digit:]]+\\.*[[:digit:]]*",str, perl=TRUE))))


> strspl
[1] -26755.22 -50150.60

If you want to store the outcome in a data-frame then you can use the below command

#everything is same but instead of as.numeric we replace it with as.data.frame
str_df <- as.data.frame(unlist(regmatches(str,gregexpr("(?>-)*[[:digit:]]+\\.*[[:digit:]]*",str, perl=TRUE))))

#it is not necessary to change the column but it is a good practice to do so
colnames(str_df) <- "variable_1"


Outcome in Dataframe

Let me know if you have any doubt, would help you.

If you got what you are looking for, you can accept the answer by clicking on the green tick mark.

  • $\begingroup$ Thank you very much. That was exactly what i was looking for. $\endgroup$
    – Viz
    Mar 12, 2018 at 10:24
  • $\begingroup$ Can you explain what is your regular expression doing? $\endgroup$
    – Ankit Seth
    Mar 12, 2018 at 10:35
  • $\begingroup$ @AnkitSeth: The regular expression works like this, it start with the decimal point and decimal fraction(optional) and allows multiple numbers to be extracted. (?>-) this is for the negative sign. hope I answered your question. Let me know if I'm not clear $\endgroup$
    – Toros91
    Mar 12, 2018 at 10:48

I just did this-

> library(stringr)
> x <- c("-26755.22-50150.60")
> matc = "\\-[0-9]*\\.[0-9]{2}"
> as.numeric(unlist(str_match_all(x, matc)))
[1] -26755.22 -50150.60

After this, you can select the numbers by using respective indexes.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.