Regex that does not allow consecutive dots

后端 未结 3 1427
我在风中等你
我在风中等你 2020-11-29 13:18

I have a Regex to allow alphanumeric, underscore and dots but not consecutive dots:

^(?!.*?[.]{2})[a-zA-Z0-9_.]+$

I also need to now allow

相关标签:
3条回答
  • 2020-11-29 13:38

    Re-write the regex as

    ^[a-zA-Z0-9_]+(?:\.[a-zA-Z0-9_]+)*$
    

    or (in case your regex flavor is ECMAScript compliant where \w = [a-zA-Z0-9_]):

    ^\w+(?:\.\w+)*$
    

    See the regex demo

    Details:

    • ^ - start of string
    • [a-zA-Z0-9_]+ - 1 or more word chars
    • (?:\.[a-zA-Z0-9_]+)* - zero or more sequences of:
      • \. - a dot
      • [a-zA-Z0-9_]+ - 1 or more word chars
    • $ - end of string
    0 讨论(0)
  • 2020-11-29 13:41

    You can try this:

    ^(?!.*\.\.)[A-Za-z0-9_.]+$
    

    This will not allow any consecutive dots in the string and will also allow dot as first and last character

    Tried here

    0 讨论(0)
  • 2020-11-29 13:54

    You can use it like this with additional lookaheads:

    ^(?!\.)(?!.*\.$)(?!.*?\.\.)[a-zA-Z0-9_.]+$
    
    • (?!\.) - don't allow . at start
    • (?!.*?\.\.) - don't allow 2 consecutive dots
    • (?!.*\.$) - don't allow . at end
    0 讨论(0)
提交回复
热议问题