Mic*_*eau 6 python regex python-3.x
我需要在字符串中的任何位置匹配以下其中一个:
${aa:bb[99]}
${aa:bb}
${aa}
Run Code Online (Sandbox Code Playgroud)
但不是:
$${aa:bb[99]}
$${aa:bb}
$${aa}
Run Code Online (Sandbox Code Playgroud)
我的python 3正则表达式是:
pattern = **r"[^\$|/^]**\$\{(?P<section>[a-zA-Z]+?\:)?(?P<key>[a-zA-Z]+?)(?P<value>\[[0-9]+\])?\}"
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是说不是$或字符串开头的正确方法.该块r"[^\$|/^]"将正确检测所有情况但如果我的字符串从第一个字符开始将失败.
我trie,没有成功:
r"[^\$|\b]...
r"[^\$|\B]...
r"[^\$]...
r"[^\$|^]
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
使用负面的lookbehind:
(?<!\$)
Run Code Online (Sandbox Code Playgroud)
然后按照你真正想要匹配的东西来跟随它.这将确保您实际想要匹配的事物不在前面$(即不匹配\$):
(?<!\$)\$\{(?P<section>[a-zA-Z]+?\:)?(?P<key>[a-zA-Z]+?)(?P<value>\[[0-9]+\])?\}
^ ^
| |
| +--- The dollar sign you actually want to match
|
+--- The possible second preceding dollar sign you want to exclude
Run Code Online (Sandbox Code Playgroud)
(?<!...)如果字符串中的当前位置前面没有匹配,则匹配
....这被称为负面的后观断言.与正向lookbehind断言类似,包含的模式必须仅匹配某些固定长度的字符串,并且不应包含组引用.以负反向断言开始的模式可以在被搜索的字符串的开头匹配.
https://docs.python.org/3/library/re.html