Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression to match any number unless it's followed by a given character

I’m stuck on creating a reg ex that matches and groups any number of digits unless it’s followed directly by a letter A

What I want:

1     -> 1
1B    -> 1
11B   -> 11
1A    -> nothing
11A   -> nothing

In the reg ex I have (https://regex101.com/r/jdlDe9/1), I use a negative look-ahead: .*(\d+)(?!A). It works if a single digit is followed by an A but still matches if multiple digits are followed by an A

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1     -> 1        OK
1B    -> 1        OK
12B   -> 12       OK
1A    -> nothing  OK
12A   -> 1        NOT OK. Here it matches the first `1` but I don't want to match anything

>Solution :

The quantifiers in the pattern .*(\d+)(?!A) allow backtracking, so the the \d+ that matches 12 in 12A can backtrack one position and have the lookahead evaluate to true.

You can match capture 1+ digits, followed by matching any char except A or a digit, or assert the end of the string

(\d+)(?:[^A\d]|$)

Regex demo

Or if possessive quantifiers are supported, that not allow backtracking after there is a match, and you can get a match only without the capture group:

\d++(?!A)

Regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading