I am trying to write a regular expression to allow numbers and only one hypen in the middle (cannot be at start or at the end)
say pattern: 02-04
, 02
are acceptable but
pattern: --
or -
or -02
or 04-
or 02-04-06
are unacceptable
I tried something like this but this would allow - at the beginning and also allow multiple -
'/^[0-9 \-]+$/'
I am not that good with regex so a little explanation would be real helpful.
EDIT: Sorry to bug you again with this but I need the numbers to be of only 2 digits (123-346) should be considered invalid.
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.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
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.
Try this one:
/^\d{1,2}(-\d{1,2})?$/
One or two digits, followed by, optionally, ( a hyphen followed by one or two digits)
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