regex second number in r

To extract the second number from a string using regular expression in R, you can use the following code:

main.r
string <- "Some text 123, 456, 789"
second_number <- regmatches(string, regexpr("\\d+(?=\\D+\\d)", string, perl=TRUE))
119 chars
3 lines

In the above code, string variable contains the input string from which we want to extract the second number. The regexpr() function returns the starting position of the first match of the regular expression in the string. The regular expression pattern \\d+(?=\\D+\\d) matches one or more digits that are followed by one or more non-digits and then again one or more digits. The (?=...) is a positive lookahead assertion that matches the digits only when they are followed by non-digits and digits.

The regmatches() function extracts the matching substring from the original string based on the starting position obtained from regexpr().

The second_number variable contains the extracted second number from the string. If the string does not contain a second number or contains only one number, the second_number variable will be NA.

gistlibby LogSnag