# How do I split number string with digit pattern?

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

How do I get two different Numbers out that string

Example:

I want separate two numbers

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


To this

-26755.22
-50150.60


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

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

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))))


Outcome:

> 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:

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

• Thank you very much. That was exactly what i was looking for. – Viz Mar 12 '18 at 10:24
• Can you explain what is your regular expression doing? – Ankit Seth Mar 12 '18 at 10:35
• @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 – Toros91 Mar 12 '18 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.