【发布时间】:2020-02-07 03:32:26
【问题描述】:
下面的正则表达式应该匹配任何start-of-string、whitespace 或: 前面的:text:,后面是end-of-string、whitespace 或:(以及一些额外的规则)
我不擅长正则表达式,但我在 regexr.com 中提出了所需的解决方案:
(?<=\s|:|^)(:[^\s|:]+:)(?=\s|:|$)
:match1::match2: :match3:
:match4:
000:matchNot:
:matchNot:000
:match Not:
结果::match1:、:match2:、:match3:、:match4:
但在 Python 3 上,这会引发错误。
re.search("(?<=\s|:|^)(:[^\s|:]+:)(?=\s|:|$)", txt)
re.error:look-behind 需要固定宽度的模式
有人知道解决这个问题的好方法吗?任何提示都表示赞赏。
【问题讨论】:
-
确保你使用
(?<![^\s:]):[^\s:]+:(?![^\s:])而不是(?:^|(?<=[\s:]))(:[^\s:]+:)(?=[\s:]|$)。
标签: regex python-3.x