ABCD
ABCD

Reputation: 43

Trying to use a regular expression in R to capture some data

So I have a table in R, and an example of of the string I am trying to capture is this:

C.Hale (79-83)

I want to write a regular expression to extract the (79-83).

How do I go about doing this?

Upvotes: 0

Views: 56

Answers (2)

akrun
akrun

Reputation: 887118

We can use sub. We match one or more characters that are not a space ([^ ]+) from the beginning of the string (^) , followed by a space (\\s) and replace it with a ''.

sub('^[^ ]+\\s', '', str1)
#[1] "(79-83)"

Or another option is stri_extract_all from stringi

library(stringi)
stri_extract_all_regex(str1, '\\([^)]+\\)')[[1]]
#[1] "(79-83)"

data

str1 <- 'C.Hale (79-83)'

Upvotes: 3

Tyler Rinker
Tyler Rinker

Reputation: 109874

One possibility using the qdapRegex package I maintain:

x <- "C.Hale (79-83)"

library(qdapRegex)
rm_round(x, extract = TRUE, include.markers = TRUE)

## [[1]]
## [1] "(79-83)"

Upvotes: 3

Related Questions