我有一个像这样的字符串
text= '{username} joined {servername} {{anytext}} '
和一个简单的正则表达式代码
print(re.findall('{([^{}]*)}', text))
#output
['username', 'servername', 'anytext']
其中 anytext
位于双括号内,但也通过正则表达式进行验证。我的意思是,正则表达式应该只查找单括号中的单词并忽略双括号。
请帮助我做到这一点。
最佳答案
您可以将字符串与正则表达式进行匹配
(?<!{{)(?<={)[^{}]*?(?=})(?!}})
如图所示,有两个匹配项:
'{username} joined {servername} {{anytext}}'
^^^^^^^^ ^^^^^^^^^^
该表达式可以分解如下。
(?<!{{) # a negative lookbehind asserts the current location
# in the string is not preceded by '{{'
(?<={) # a positive lookbehind asserts the current location
# in the string is preceded by '{'
[^{}]*? # match zero or more characters other than '{' and '}'
(?=}) # a positive lookahead asserts the current location
# in the string is followed by '}'
(?!}}) # a negative lookahead asserts the current location
# in the string is not followed by '}}'
如果需要,消极的环视可以嵌入到积极的环视中:
(?<=(?<!{{){)[^{}]*?(?=}(?!}))
首先可以通过将字符串与以下正则表达式进行匹配来测试该字符串是否具有平衡的大括号。
^[^{}]*(?:(?:{[^{}]*}|{{[^{}]*}})[^{}]*)*$
将光标悬停在链接处表达式的每个部分上以获得其功能的说明。
关于python - 在python中使用正则表达式仅在单括号中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70951534/