質問

I'd appreciate if someone could help..

I need to allow the occurrence of dash (-) in any position of the string (except the beginning).

My RegEx is:

^[+]?[0-9]{3,10}$

I want to allow the following possibilities:

+7-777-77777
7-7-7-7-7-77

etc. so that I could have dash in any place after plus (+) and first digit.

Thank you in advance!

役に立ちましたか?

解決

You can use lookahead

^(?=([^\d]*\d){3,10}[^\d]*$)[+]?\d+(-\d+)*$
 --------------------------
           |
           |->match further only if there are 3 to 10 digits in string

This would match string with three to 10 digits optionally having - in between the string


try it here


If you want optional space in between the strings

^(?=([^\d]*\d){3,10}[^\d]*$)[+]?\d+(\s*-\s*\d+)*$

他のヒント

http://rubular.com/r/8eyAolNHlX
In Ruby it should Works:

  /\+?(?:\d\-?\d?)+/

Maybe this?

^[+]?\d(-?\d){2,9}$

I think the pattern you're looking for is this:

^[+]?[0-9][0-9-]{2,9}$

This will match an optional plus, followed by a decimal digit, followed 2 to 9 decimal digits or hyphens.

If you also want to ensure that the string doesn't end with a hyphen, simply use this:

^[+]?[0-9][0-9-]{1,8}[0-9]$

This will match an optional plus, followed by a decimal digit, followed 1 to 8 decimal digits or hyphens, followed by a decimal digit.

Note you can also extend this to all Unicode digits (see this answer for more information):

^\+?\d[\d-]{2,9}$

or

^\+?\d[\d-]{1,8}\d$

This requires the input start and end with a digit with optional plus at front

^\+?\d[\d-]{,8}\d$
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top