python - 在python中使用正则表达式仅在单括号中查找单词

标签 python regex

我有一个像这样的字符串

text= '{username} joined {servername} {{anytext}} '

和一个简单的正则表达式代码

print(re.findall('{([^{}]*)}', text))

#output
['username', 'servername', 'anytext']

其中 anytext 位于双括号内,但也通过正则表达式进行验证。我的意思是,正则表达式应该只查找单括号中的单词并忽略双括号。

请帮助我做到这一点。

最佳答案

您可以将字符串与正则表达式进行匹配

(?<!{{)(?<={)[^{}]*?(?=})(?!}})

Demo

如图所示,有两个匹配项:

'{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 '}}' 

如果需要,消极的环视可以嵌入到积极的环视中:

(?<=(?<!{{){)[^{}]*?(?=}(?!}))

首先可以通过将字符串与以下正则表达式进行匹配来测试该字符串是否具有平衡的大括号。

^[^{}]*(?:(?:{[^{}]*}|{{[^{}]*}})[^{}]*)*$

Demo

将光标悬停在链接处表达式的每个部分上以获得其功能的说明。

关于python - 在python中使用正则表达式仅在单括号中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70951534/

相关文章:

python - Python 的交换符号中的顺序重要吗? (a, b = b, a)

java - 从java字符串中高效提取数字(已经尝试过 Guava 和正则表达式)

python - 如何通过美丽汤抓取此页面?

java - 正则表达式匹配a-字母数字&b-数字&c-数字

ios - Swift - 如何将 'shouldChangeTextInRange' 与 Firebase 一起用于实时搜索?

javascript - 找到某些/特定的换行符,同时忽略其他换行符

java正则表达式不以点结尾的单词

python - 如何获取 youtube 混合播放列表?

python - 获取轮廓最高点的坐标

python - 为什么要避免 exec() 和 eval()?