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?
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.
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.
\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.
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).
See it in action: Regexr.com
^[0-9]+(-[0-9]+)+$
1-2
1-2-3
1
1-
1-2-
1-2----3
1---3
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.
Use the normal*(special normal*)*
pattern:
^[0-9]+(-[0-9]+)+$
where normal
is [0-9]
and special
is -
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With