RD Ward
RD Ward

Reputation: 6737

Is it possible for a Regular Expression to Lookahead OR Lookbehind?

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?

Upvotes: 2

Views: 832

Answers (2)

HamZa
HamZa

Reputation: 14921

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.

First of all, I will just warn you that you should just go with the following: (?<=b)a|a(?=b). It's simple and easy to follow.

Now if you want to see another solution, I've come up with the following a(?(?=b)|(?<=b.)). So what does this mean ?

a               # match a
(?              # if
    (?=b)       # there is a "b" ahead
    |           # else
    (?<=b.)     # there is a "b" 2 steps behind
)               # end if

Online demo

Upvotes: 2

Dan Bron
Dan Bron

Reputation: 2324

The matching set seems the simplest and clearest approach to me. That said, you could always build a lookahead-only regex and then apply it to both the target string and its reverse.

Upvotes: 1

Related Questions