Nunnsy
Nunnsy

Reputation: 146

Ignoring prefix if it exists for regex match, then continue matching

I want to match the first 1 to 3 characters of set [A-Z], but I want to ignore the prefix XYZ_.

Example:

I'm trying to use a negative lookahead of the form ^(?!XYZ_)?[A-Z]{1,3}. However, this will return 'XYZ' from the first two examples (works fine for the other examples). I.e. its output is:

How can I ignore a prefix (if it exists) from a string and match on the condition I'm looking for after it?

Upvotes: 1

Views: 134

Answers (1)

Nunnsy
Nunnsy

Reputation: 146

It turns out this is somewhat Python specific to the re module.

I was able to achieve my desired outcome using \K which resets the starting point of the reported match.

As such, if using the Perl Compatible Regex Expression (PCRE), the answer is: ^(?:XYZ_\K)?[A-Z]{1,3}

More can be read here

Upvotes: 1

Related Questions