Arepa Slayer
Arepa Slayer

Reputation: 443

C# regex to match string

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

Answers (3)

Shiva Garg
Shiva Garg

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

Nicholas Carey
Nicholas Carey

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

mellamokb
mellamokb

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

Related Questions