2

I'm struggling to create some kind of RegEx that can either look ahead or look behind.

Something ideal would be to match the a in both ab and ba, triggered by the presence of the b.

Obviously I could repeat the a, such as:

((?<=b)a)|a(?=b) 

But can it be done without the repetition of the matching set?

4

2 回答 2

2

免责声明:此答案使用PCRE语法/风格。语法可能与其他风格不同,其中一些根本不支持它。

首先,我会警告您,您应该使用以下内容:(?<=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

Online demo

于 2013-10-30T18:04:24.980 回答
1

匹配集对我来说似乎是最简单和最清晰的方法。也就是说,您始终可以构建一个仅向前看的正则表达式,然后将其应用于目标字符串及其反向字符串。

于 2013-10-30T16:38:34.433 回答