David542
David542

Reputation: 110382

0 or n occurrences, but nothing else

How would I do the following, to match either 2 or 0 digits?

[0-9]{0,2}

This is what I have so far, but this will match 0, 1, or 2 occurrences. I only want 0 or 2.

Upvotes: 1

Views: 73

Answers (3)

Jongware
Jongware

Reputation: 22478

Too easy (if you know how):

(\d\d)?

If this is in the context of an entire string, use

^(\d\d)?$

Inside another string, add boundaries:

(\b\d\d\b)?

Upvotes: 3

Martin Konecny
Martin Konecny

Reputation: 59681

In the general case you could do

([0-9]{2}|[0-9]{0})  # place the {2} before {0} so that it tries that first.

In this particular case, since one of your matches is zero, take a look at @"Greg Hewgill"'s answer.

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 994021

You could do the following:

([0-9]{2})?

Upvotes: 5

Related Questions