我正在努力创建某种可以向前看或向后看的正则表达式。
理想的情况是匹配 ab 和 ba 中的 a,由 b 的存在触发强>.
显然我可以重复a,例如:
((?<=b)a)|a(?=b)
但是不重复匹配集可以做到吗?
最佳答案
Disclaimer: This answer is using the PCRE syntax/flavor. The syntax may differ from other flavors and some of them don't support it at all.
首先,我只是警告您,您应该选择以下内容:(?<=b)a|a(?=b)
。它简单易懂。
现在,如果您想查看另一个解决方案,我想出了以下 a(?(?=b)|(?<=b.))
。那么这意味着什么?
a # match a
(? # if
(?=b) # there is a "b" ahead
| # else
(?<=b.) # there is a "b" 2 steps behind
) # end if
关于regex - 正则表达式是否可以进行 Lookahead 或 Lookbehind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19688681/