Reputation: 1061
I'm using the following regex to match strings inside brackets:
\((.*?)\)
But this matches this:
(word)
and this too:
( word )
I need to modify it to only match the first case: words inside brackets with no spaces around: (word)
Any ideas?
Thanks in advance
Upvotes: 1
Views: 5062
Reputation: 89547
You can use this pattern:
\([^\s()](?:[^()]*[^\s()])?\)
[^\s()]
ensures that the first character isn't a whitespace or brackets (and make mandatory at least one character).
(?: [^()]* [^\s()] )?
is optional. if it matches, the same character class ensures that the last character isn't a whitespace.
Upvotes: 2
Reputation: 726479
Use lookahead/lookbehind to disallow space after the opening parenthesis and before the closing parenthesis:
\((?!\s)[^()]+(?<!\s)\)
(?!\s)
and (?<!\s)
mean "not followed by / not preceded by a space".
The part in the middle, [^()]+
requires one or more characters to be present between parentheses, disallowing ()
match.
Upvotes: 1