senna
senna

Reputation: 329

regular expression pattern handling brackets

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.:

I've tried the following: "\s*\(.*\)" But I am somehow wrong with my idea!

Upvotes: 1

Views: 109

Answers (3)

davidrac
davidrac

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

Ωmega
Ωmega

Reputation: 43703

Try regex (?:^|\))\s*([^\(\)]+?)\s*(?:\(|$)

Upvotes: 0

murgatroid99
murgatroid99

Reputation: 20297

A regex for finding the text between two parenthesized groups is

/(?:^|\([^)]*\))([^(]*)(?:$|\([^)]*\))/m

The breakdown is a follows:

  1. Start with some text in parentheses or the beginning of a line: (?:^|\([^)]*\)). This matches from an open paren to the first closed paren
  2. Then match the text outside of the parentheses, and put it in a group ([^(]*). This matches up to the next open paren.
  3. Then match more text in parentheses or the end of a line: (?:$|\([^)]*\))

I used multiline mode (m) so that ^ and $ would match line breaks as well as the start and end of the string

Upvotes: 0

Related Questions