Possible Duplicate:
Extract info inside all parenthesis in R (regex)
I have a string
df
Peoplesoft(id-1290)
I like to capture characters between the parentesis, for example. I like to get id-1290 from the above example.
I used this:
x <- regexpr("\\((.*)\\)", df)
this is giving me numbers like
[1] 10
Is there an easy way to grab text between parentesis using regex in R?
Here is a slightly different way, using lookbehind/ahead:
df <- "Peoplesoft(id-1290)"
regmatches(df,gregexpr("(?<=\\().*?(?=\\))", df, perl=TRUE))
Difference with Andrie's answer is that this also works to extract multiple strings in brackets. e.g.:
df <- "Peoplesoft(id-1290) blabla (foo)"
regmatches(df,gregexpr("(?<=\\().*?(?=\\))", df, perl=TRUE))
Gives:
[[1]]
[1] "id-1290" "foo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With