如何使用 RegExp 确定子字符串是否位于括号之间?
可能是重复的;我以为这个问题一定有人问过,但我搜索了一下却找不到。
如何使用正则表达式确定子字符串是否位于括号之间?
假设我想检查以下句子中的文本“fox”是否被括号括起来:
The (quick) brown fox jumps (over the lazy) dog.
我尝试了这个正则表达式,但是当“fox”实际上没有括号但左右有括号时,它测试为真:
\(.*?fox.*?\)
我尝试使用负向后查找和负向前查找,但它也不起作用:
\(.*?(?<!\)).*?fox.*?(?!\().*?\)
Might be a duplicate; I thought this question had to have been already asked, but I searched and couldn’t find one.
How do you determine, using RegExp, whether or not a substring is between parentheses?
Say I want to check if the text “fox” is surrounded by parentheses in the following sentence:
The (quick) brown fox jumps (over the lazy) dog.
I tried this RegEx, but it tests true when “fox” is actually not parenthesized but does have parentheses to its left and right:
\(.*?fox.*?\)
I tried it with negative lookbehind and negative lookahead, and it doesn’t work either:
\(.*?(?<!\)).*?fox.*?(?!\().*?\)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种保证该单词仅存在于内括号中而不存在于嵌套内容中的方法:
https://regex101 .com/r/UlQpM6/1
\([^()]*fox[^()]*\)
\(
-打开[^()]*
- 0 个或多个非括号的任何字符fox
- Fox[^()]*
-重复模式\)
- 关闭Here's a way to guaranteed that the word exists in inner parentheses only without existing in something nested:
https://regex101.com/r/UlQpM6/1
\([^()]*fox[^()]*\)
\(
- Open[^()]*
- 0 or more of any character that isn't parenthesesfox
- fox[^()]*
- repeat pattern\)
- Close这将匹配括号中的任何术语:
(快速)棕色狐狸跳(超过)懒狗。
这个问号将确保正则表达式是“惰性的”并且仅匹配右括号的第一个实例。
像这样删除问号:
\(.*\)
将为您提供以下匹配项,这可能不是您想要的:(快速)棕色狐狸跳(过)懒狗。
如果您实际上只想匹配“(fox)”,那么正确的正则表达式是:
您可以使用在线正则表达式测试器或文本编辑器来回答此类问题。
This will match any term in parenthesis:
The (quick) brown fox jumps (over) the lazy dog.
This question mark will ensure that the regex is 'lazy' and will only match the first instance of a closing parenthesis.
Removing the question mark like this:
\(.*\)
will give you the following match, which is probably not what you want:The (quick) brown fox jumps (over) the lazy dog.
If you literally only want to match "(fox)", then the correct regex is:
You can use an online regex tester or text editor to answer these kind of questions.