-2

Given two regexs expr1 and expr1, can we write a lookbehind (?<=expr1)expr2 equivalently in terms of the if-then-else construct?

For example, is the lookbehind (?<=expr1)expr2 equivalent to (expr1)(?(-1)expr2|expr3), where expr3 is some regex which is never possible to match?

In other words, are the two regex's (?<=expr1)expr2 and(expr1)(?(-1)expr2|expr3) describe the same?

If yes, how do you choose expr3, so that it is never possible to match?

Thanks?

Tim
  • 1
  • 141
  • 372
  • 590

1 Answers1

1

Do the two regex's (?<=expr1)expr2 and (expr1)(?(-1)expr2|expr3) describe the same?

No. They match different strings.

(?<=expr1)expr2 can only ever match one thing: expr2, and not just anywhere: the expr2 in expr1expr2.

In contrast, (expr1)(?(-1)expr2|expr3) can only ever match: expr1expr2.

Clearly, expr2 and expr1expr2 are different strings. The answer is no.

..but the other answer is Yes:

Can we write a lookbehind (?<=expr1)expr2 equivalently in terms of the if-then-else construct?

Yes. This uses in an-then-else (the else is implied): (?(?<=expr1)expr2), and it too matches expr1expr2. Of course, it too uses a lookbehind.

The "implied else" doesn't sound right to you? Add a |, as in (?(?<=expr1|)expr2)

What about expr3?

Your last regex (expr1)(?(-1)expr2|expr3) will never be able to match expr3. If you want it to have a chance, you would have to make the capture group optional: (expr1)?(?(-1)expr2|expr3)

zx81
  • 41,100
  • 9
  • 89
  • 105