简体   繁体   中英

C# regex to match string

I'm currently having difficulty matching strings with my regex. The objective is to match:

  • One or two letters
  • One, two or three numbers
  • Zero or one asterisk

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:

  • 3.0L
  • 6HBW20
  • 3/8"
  • Y1015

I'm not too bright with regex, but this is holding me from completing my project. Can anyone help me out?

Thank you.

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 :)

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}[*]?$"

\\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}\*?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM