I want to create a regular expression in such a way that only hypens and digits must be allowed in the text box t开发者_JAVA百科he criteria is
- Hypen should not come in the first and last position
- Hypen must have digits at both ends
- There can be n number of hypens and digits in the text box
Thanks in advance
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
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.
I assume that an empty string is valid. I'm not sure I understand your third clause; do you mean that n can be anything, or do you have to limit things to n occurrences? I'm also not sure how many digits need to be at each end of a hyphen; is it any number one or greater, or exactly one?
The following regex allows a string like 1-9-129-2-293-23, for example.
^(([0-9]+-[0-9]+)|[0-9]+)*$
Because each subpattern must start and end with a digit, it's not necessary to have a digit match at each end outside the substring as in the other solutions posted here.
^((\d+-)+\d+)*$
It says: you must start with a few digits, followed by a -
. Repeat as many times as you like, then you must end with some more digits. That *
at the end is there to allow empty strings.
Would this work?
(\d+\-)*\d+
Edit: Changed '+' to '*' as hyphens don't seem to be necessary.
Edit2: Fixed the regex to prevent double hyphens.
I can't believe it, I got it by giving a guess in regular expression i hope this will work fine.
(\d+(\d*\\-\d+)+\d*)|\d+
You could try using this regex: .[\w-]*
精彩评论