Regex不应该匹配连续的_或-或它们的连续组合

问题描述 投票:1回答:1

我正在尝试使用以下规则制作正则表达式:

字符串只能包含[a-zA-Z0-9_-]字符串不应以-_开头。字符串不能具有连续的-_。字符串不能包含-_的连续组合。

某些情况下,正则表达式应该通过并失败:

_My-Random_String // FAIL starts with _
-My-Random_String // FAIL starts with -
My-_Random_String // FAIL has a consecutive combination of - and _
My-Random_-String // FAIL has a consecutive combination of _ and -
My--Random_String // FAIL has a consecutive `-`
My-Rand__om-String // FAIL has a consecutive `_`
My_R-a_ndom-StrIng // PASS

我不确定如何自己制作此正则表达式,因为我只有基本的正则表达式技能。

到目前为止,我已经尝试过:

^[a-zA-Z\d]+(?:[-_]{1}[a-zA-Z\d])+$

我很难找到连续的_-或连续的_-的组合,对于这些情况,我的正则表达式将失败。

regex pcre
1个回答
1
投票

您可以使用

^(?=.{1,30}$)[a-zA-Z0-9]+(?:[-_][a-zA-Z0-9]+)*$

请参见regex demo

详细信息

  • ^-字符串开头
  • (?=.{1,30}$)-字符串必须有1到30个字符,但字符串结尾处的换行符除外
  • [a-zA-Z0-9]+-1+个字母数字字符
  • (?:[-_][a-zA-Z0-9]+)*-0或多个重复
    • [[-_]-下划线或连字符
    • [a-zA-Z0-9]+-1+个字母数字字符
  • [$-字符串结尾。

0
投票

正则表达式模式应为:

^(?=.{1,30}$)(?![_-])(?!.*[_-]{2})[a-zA-Z0-9_-]+(?<![_-])$
 └─────┬────┘└───┬──┘└─────┬─────┘└─────┬─────┘ └───┬───┘
       │         │         │            │           no _ or - at the end
       │         │         │            │
       │         │         │            allowed characters
       │         │         │
       │         │         no __ or _- or -_ or -- inside
       │         │
       │         no _ or - at the beginning
       │
       string is 1-30 characters long

您已经编辑了问题,删除了长度限制。

上面的模式在开头指定了.{1,30},并指定了这些限制。

如果您想不同地限制长度,可以将其更改为.{min,max}.{min,}.{,max},其中minmax为数字。

© www.soinside.com 2019 - 2024. All rights reserved.