1

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.

1
  • Are you matching these strings inside of a larger block of text, or is it the whole string? Commented Sep 11, 2014 at 0:13

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.