raklos
raklos

Reputation: 28545

Creating a regex that allows 9 or 10 digits

I need help with a regex

I need it to match either a 9 or 10 digit value that starts with 50.

I have:

^[ ]*(50)[0-9]{7}[ ]*$

which allows 9 digits.

How can I expand this so that it also allows 10 digits?

Upvotes: 3

Views: 5533

Answers (4)

psxls
psxls

Reputation: 6925

Add the range {7,8}

^[ ]*(50)[0-9]{7,8}[ ]*$

FYI this site describes the standard quantifiers that you can use in a regular expression:

* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times

Upvotes: 6

Ewan
Ewan

Reputation: 15058

This regex will match what you need:

^\s*50\d{7,8}\s*$

This will match all 9 or 10 digit numbers starting with 50 with an unlimited number of spaces before, or after, them on the line.

If you want to match all 9 or 10 digit numbers starting with 50 regardless of position and number of spaces etc then:

50\d{7,8}

will do exactly what you need.

Upvotes: 3

user2704193
user2704193

Reputation:

Here's what you need: (50)\d{7,8}

Upvotes: 1

hsz
hsz

Reputation: 152206

Try with following regex:

^[ ]*50\d{7,8}[ ]*$

Upvotes: 3

Related Questions