'How can I extract the numbers from this string?

The question I'm asking is in string1:

string1 <- "We have to extract these numbers 12, 47, 48 The integers numbers are also interesting: 189 2036 314 \',\' is a separator, so please extract these numbers 125,789,1450 and also these 564,90456 We like to offer you 7890$ per month in order to complete this task... we are joking"


str_match_all(string1,"[0-9]{2}")

output looks like this

[[1]]
      [,1]
 [1,] "12"
 [2,] "47"
 [3,] "48"
 [4,] "18"
 [5,] "20"
 [6,] "36"
 [7,] "31"
 [8,] "12"
 [9,] "78"
[10,] "14"
[11,] "50"
[12,] "56"
[13,] "90"
[14,] "45"
[15,] "78"
[16,] "90"

but I need it to look like this

 [1,] "12"   
 [2,] "47"   
...
[12,] "7890"



Solution 1:[1]

Here's what you want:

library(magrittr)
gsub("\\D", "", strsplit(string1, split="[ ,\\$]")[[1]]) %>% { .[. != ""] }

Package magrittr is what gives you the pipe operator %>% that allows you to do this all on one line.

Generally, I find it best to chip away at the unwanted parts of a string rather than to try to identify the parts that I want by way of a regular expression. In this case, the string in your example first gets split into 57 pieces by the strsplit function, based on three separators. Some of those pieces are numeric, and others aren't. The gsub turns all the non-numeric ones into blank strings (""). This is piped to the last step, where only the non-blank strings are extracted.

And voila!

> gsub("\\D", "", strsplit(string1, split="[ ,\\$]")[[1]]) %>% { .[. != ""] }
 [1] "12"    "47"    "48"    "189"   "2036"  "314"   "125"   "789"   "1450"
[10] "564"   "90456" "7890"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emmanuel