Regex to match strings inside brackets with no spaces around

给你一囗甜甜゛ 提交于 2021-01-28 05:07:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!