Regex不应该匹配_或-或它们的保守组合

问题描述 投票:0回答: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个回答
0
投票

您可以使用

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

请参见regex demo

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