Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex number and hyphen

Tags:

regex

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?

like image 601
vusan Avatar asked Dec 25 '12 13:12

vusan


People also ask

How do you use a hyphen in regex?

In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

Can you use regex with numbers?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

How do you match a number in regex?

\d for single or multiple digit numbers To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

How do you denote special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


3 Answers

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
like image 105
mmdemirbas Avatar answered Oct 17 '22 01:10

mmdemirbas


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.

like image 20
Rohit Jain Avatar answered Oct 17 '22 01:10

Rohit Jain


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

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

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

like image 40
fge Avatar answered Oct 17 '22 02:10

fge