Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to allow numbers and only one hyphen in the middle

Tags:

regex

php

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 , 02are 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.

like image 389
ro ko Avatar asked Aug 23 '12 10:08

ro ko


People also ask

How do you handle 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.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What does regex 0 * 1 * 0 * 1 * Mean?

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.

Can you use regex on 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.


1 Answers

Try this one:

/^\d{1,2}(-\d{1,2})?$/

One or two digits, followed by, optionally, ( a hyphen followed by one or two digits)

like image 175
Oussama Jilal Avatar answered Sep 18 '22 06:09

Oussama Jilal