views:

81

answers:

2

I am not too familiar with regex and so I been having some getting this to work with Apple's NSRegularExpression

I am trying to remove words in parentheses or brackets...

For example:

NSString *str = @"How do you (remove parentheses words) within a string using"

resulting string should be: @"How do you within a string using"

Thanks you!!!

+2  A: 

Search for

\([^()]*\)

and replace with nothing.

As a verbose regex:

\(      # match an opening parenthesis
[^()]*  # match any number of characters except parentheses
\)      # match a closing parenthesis

This will work fine if parentheses are correctly balanced and unnested. If parentheses can be nested (like this (for example)), then you need to re-run the replace until there are no further matches, since only the innermost parentheses will be matched in each run.*

To remove brackets, do the same with \[[^[\]]*\], for braces \{[^{}]*\}.

With conditional expressions you could do all three at once, but the regex looks ugly, doesn't it?

(?:(\()|(\[)|(\{))[^(){}[\]]*(?(1)\))(?(2)\])(?(3)\})

However, I'm not sure if NSRegularExpression can handle conditionals. Probably not. Explanation of this monster:

(?:           # start of non-capturing group (needed for alternation)
 (\()         # Either match an opening paren and capture in backref #1
 |            # or
 (\[)         # match an opening bracket into backref #2
 |            # or
 (\{)         # match an opening brace into backref #3
)             # end of non-capturing group
[^(){}[\]]*   # match any number of non-paren/bracket/brace characters
(?(1)\))      # if capturing group #1 matched before, then match a closing parenthesis
(?(2)\])      # if #2 matched, match a closing bracket
(?(3)\})      # if #3 matched, match a closing brace.

*You can't match arbitrarily nested parentheses (since these constructs are no longer regular) with regular expressions, so that's not a limitation of this regex in particular but of regexes in general.

Tim Pietzcker
Thanks for the explanation buddy! This helps a lot!
Unikorn
For this example: (like this (for example))NSString *match = @"\\(.*\\)"; seems to work.
Unikorn
Yes, but it will fail on `keep (remove) keep (remove) keep` - it matches from the first to the last parenthesis, removing the middle `keep`! You can't match irregular languages with regular expressions. Some flavors (like Perl or .NET) make recursive matching possible, but it's almost always a bad idea. This is not what regexes were made for.
Tim Pietzcker
Thanks for pointing that out!
Unikorn
+2  A: 

I don't know objectice-c regex flavor but in PCRE you can do :

s/\[.*?\]|\(.*?\)|\{.*?\}//g

This will replace everything between parentheses or brackets by empty string.

M42
This is not going to work. It will match `(xxx(` or `[yyy[` but not `(xxx)` or `[yyy]`.
Tim Pietzcker
@Tim: You're right, updated answer.
M42
Thanks for the responses!
Unikorn