1

I have an string like 1566-02, where -02 is optional. If I use a regular expression like this

1566\s*-\s*\d{2} 

it will always expect 2 numeric number with hyphen after 1566.

How I can make the -02 part optional, so that the IsMatch should be true for 1566 also?

For example - The value of IsMatch should be true if we pass the string as 1566 or 1566-02 or 1566-45 IsMatch value should be false for 1566-AC or 1566-

1
  • Please specify what language / platform you're using. Given that you mentioned IsMatch is this .NET? Commented Apr 9, 2014 at 21:47

1 Answer 1

3

Simply wrap it in a group and make it optional with the zero-or-one quantifier (?):

1566(\s*-\s*\d{2})? 

To prohibit any other characters before or after the matched string, use start (^) and end ($) anchors:

^1566(\s*-\s*\d{2})?$ 
Sign up to request clarification or add additional context in comments.

2 Comments

IsMatch value should be - true for 1566, 1566-23 but it should be false for 1566-AB. In this case everything becomes true
Thank you so much p.s.w.g - it meets my requirement

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.