Search code examples
regexregular-language

Regex to allow any occurrence of one symbol in any position of the string?


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!


Solution

  • 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+)*$