问题
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
回答1:
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.
Demo.
回答2:
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.
回答3:
• Word Boundaries
\(\b[^)]+\b\)
来源:https://stackoverflow.com/questions/46262902/regex-to-match-strings-inside-brackets-with-no-spaces-around