vusan
vusan

Reputation: 5331

Regex number and hyphen

I'm trying to match number with regular expression like:

34-7878-3523-4233

with this:

^[0-9][0-9-]*-[0-9-]*[0-9]$

But the expression also allow

34--34--------88

So how can I allow only one hyphen between the number?

Upvotes: 9

Views: 50586

Answers (3)

mmdemirbas
mmdemirbas

Reputation: 9158

Your regex:

See it in action: Regexr.com

^[0-9]+(-[0-9]+)+$

Matches:

1-2
1-2-3

Doesn't match:

1
1-
1-2-
1-2----3
1---3

Upvotes: 28

fge
fge

Reputation: 121730

Use the normal*(special normal*)* pattern:

^[0-9]+(-[0-9]+)+$

where normal is [0-9] and special is -

Upvotes: 4

Rohit Jain
Rohit Jain

Reputation: 213261

That's because, you have included the hyphen in the allowed characters in your character class. You should have it outside.

You can try something like this: -

^([0-9]+-)*[0-9]+$

Now this will match 0 or more repetition of some digits followed by a hyphen. Then one or more digits at the end.

Upvotes: 8

Related Questions