Reputation: 13
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-
Upvotes: 1
Views: 44
Reputation: 149020
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})?$
Upvotes: 3