Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression using hypens and digits

I want to create a regular expression in such a way that only hypens and digits must be allowed in the text box the criteria is

  1. Hypen should not come in the first and last position
  2. Hypen must have digits at both ends
  3. There can be n number of hypens and digits in the text box

Thanks in advance

like image 413
Mathew Paul Avatar asked Dec 16 '22 19:12

Mathew Paul


2 Answers

Here's a shortened version of @El Yobo's regex. You can replace [0-9] with \d and you can make the hyphen optional with -? to remove the special case of hyphenless strings.

^\d+(-?\d+)*$

http://ideone.com/SRqPW

like image 92
moinudin Avatar answered Jan 04 '23 22:01

moinudin


This regular expression should do it:

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

This will match one or more digits, that may be followed by zero or more sequences of a hyphen followed by one or more digits.

like image 23
Gumbo Avatar answered Jan 04 '23 22:01

Gumbo