开发者

Regular expression using hypens and digits

开发者 https://www.devze.com 2023-01-28 16:01 出处:网络
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

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

  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


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-]*

0

精彩评论

暂无评论...
验证码 换一张
取 消