Reputation: 443
I'm currently having difficulty matching strings with my regex. The objective is to match:
Such as U21, F305 and H12*. The regex that I'm using is:
\D{1,2}\d{1,3}\*?
However, it's been matching strings like:
I'm not too bright with regex, but this is holding me from completing my project. Can anyone help me out?
Thank you.
Upvotes: 1
Views: 87
Reputation: 61
Try using /^[a-zA-Z]{1,2}\d{1,3}\*?$/
The anchors ^ and $ are useful to make sure that you match exactly the pattern you intend. Read up on them :)
Upvotes: 4
Reputation: 74177
You need to anchor your match. ^
anchors the match to start of line; $
drops anchor at end of line.
Try this regular expression
@"^[\p{L}]{1,2}\d{1,3}[*]?$"
Upvotes: 1
Reputation: 56769
\D
matches any non-digit, which is a much larger set than just letters (basically everything else, including periods, slashes, etc). Try using [a-zA-Z]{1,2}
to match 1 or 2 letters.
[a-zA-Z]{1,2}\d{1,3}\*?
Upvotes: 0