GregH
GregH

Reputation: 12868

How do I match a regex based on the priority of the expression?

If I have the following data:

abc1dogs
a1cat2dogs
turtles

and I want to extract all text either following a "1" a "2" or if the line does not contain a "1" or a "2"? The additional rule that needs to be used is that if a "1" and a "2" exist in the record then I want only the value after the "2" to be extracted. I tried using:

(?<=[12])(.*)

That came close but it returned:

dogs
cat2dogs

What I want it to return is:

dogs
dogs
turtles

Upvotes: 0

Views: 62

Answers (2)

Tulains C&#243;rdova
Tulains C&#243;rdova

Reputation: 2639

Simple

[^12\n]*$

Tested like this:

enter image description here

Upvotes: 0

Martin Ender
Martin Ender

Reputation: 44259

This slightly bloated one works with a PCRE regex engine:

(?<=2).*|(?<=1)[^2]*$|^[^12]*$

It makes sure that (if it found a 1) the rest of the string does not contain 2s. Likewise, if the whole string is to be matched, there are no 1s and 2s allowed in the string.

Upvotes: 2

Related Questions