Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to pickout some text between parenthesis [duplicate]

Tags:

regex

r

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?

like image 292
user1471980 Avatar asked Nov 21 '12 17:11

user1471980


1 Answers

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" 
like image 129
Sacha Epskamp Avatar answered Sep 27 '22 22:09

Sacha Epskamp