Reputation: 329
I am looking for a regular expression pattern that is able to handle the following problem:
(to make someone) happy (adj.)
I only want to get the word "happy" and the regular expression pattern should also handle lines if only one part is in brackets e.g.:
(to make someone) happy
happy (adj.)
I've tried the following: "\s*\(.*\)"
But I am somehow wrong with my idea!
Upvotes: 1
Views: 109
Reputation: 10738
This one will get you the right word in the first capturing group in all three options:
(?:\([^)]*\)\s*)?(\w+)(?:\s*\([^)]*\))?
You can adjust and be more permissive in case you'd like to get a couple of words or to allow special characters:
(?:\([^)]*\)\s*)?([^()\n]+)(?:\s*\([^)]*\))?
Upvotes: 2
Reputation: 20297
A regex for finding the text between two parenthesized groups is
/(?:^|\([^)]*\))([^(]*)(?:$|\([^)]*\))/m
The breakdown is a follows:
(?:^|\([^)]*\))
. This matches from an open paren to the first closed paren([^(]*)
. This matches up to the next open paren.(?:$|\([^)]*\))
I used multiline mode (m
) so that ^
and $
would match line breaks as well as the start and end of the string
Upvotes: 0