jojuk
jojuk

Reputation: 127

Regex to match either 4 or 5 digits before a letter

I need to match either letter A preceded by 1-5 digits or letter B preceded by 1-4 digits.

So my regex looks like this: (\d{1,5}A)|(\d{1,4}B)

But this matches the last 4 digits before an A.

Any solutions?

Upvotes: 3

Views: 2336

Answers (2)

vrn53593
vrn53593

Reputation: 308

Something along the lines of:

(\d{1,5}A)|(\d{1,4}B)

I would advise taking a look at cheatsheet. if you are unfamiliar with regular expressions and try to do these kind of simple regexs yourself.

There is also plenty of online regex testing apps such as: regextester which enable you to test your regexes without writing any code.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

this matches the last 4 digits before an A

Require the item before your regex to not be preceded by a digit:

(?<!\d)((\d{1,5}A)|(\d{1,4}B))

Another solution is to require a word boundary with \b.

lookahead/lookbehind tutorial

Upvotes: 4

Related Questions