Regex to disallow more than 1 dash consecutively

前端 未结 5 961
误落风尘
误落风尘 2020-11-28 10:44
  1. How can I disallow -- (more than 1 consecutive -)? e.g. ab--c
  2. - at the back of words not allow, e.g. abc-<
相关标签:
5条回答
  • 2020-11-28 11:15

    If “-” is not allowed at the beginning nor end of the string, you are searching for a sequence of “one or more alanum, followed by one or more group(s) of one dash followed by 1 or more alanum”

    /[0-9A-Z]+(-[0-9A-Z]+)+/
    

    Simple is a valuable motto with regular expressions. (nota : to search small case characters, add them. I didn't for clarity)

    0 讨论(0)
  • 2020-11-28 11:24
    ^(?!-)(?!.*--)[A-Za-z0-9-]+(?<!-)$
    

    Explanation:

    ^             # Anchor at start of string
    (?!-)         # Assert that the first character isn't a -
    (?!.*--)      # Assert that there are no -- present anywhere
    [A-Za-z0-9-]+ # Match one or more allowed characters
    (?<!-)        # Assert that the last one isn't a -
    $             # Anchor at end of string
    
    0 讨论(0)
  • 2020-11-28 11:27

    ^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$

    Using this regular expression, the hyphen is only matched just inside the group. This hyphen has the [A-Za-z0-9]+ sub-expression appearing on each side. Because this sub-expression matches on one or more alpha numeric characters, its not possible for a hyphen to match at the start, end or next to another hyphen.

    0 讨论(0)
  • 2020-11-28 11:28

    Try: ^([a-zA-Z0-9]+[-]{1})*[a-zA-Z0-9]+$

    Regex101 link: https://regex101.com/r/xZ2g6p/1

    This allows only one hyphen inbetween two set of characters and blocks it at the beginning & at the end of the character set.

    0 讨论(0)
  • 2020-11-28 11:33
    ^[a-zA-Z0-9](?!.*--)[a-zA-Z0-9-]*[a-zA-Z0-9]$
    
    ^[a-zA-Z0-9]     /*Starts with a letter or a number*/
    (?!.*--)         /*Doesn't include 2 dashes in a row*/
    [a-zA-Z0-9-]*    /*After first character, allow letters or numbers or dashes*/
    [a-zA-Z0-9]$     /*Ends with a letter or a number*/
    

    Matches:

    Re-play / Re-play-ed

    Doesn't Match:

    Replay- / Re--Play / -Replay

    0 讨论(0)
提交回复
热议问题