提问人:Kenneth R. Jones 提问时间:11/8/2023 最后编辑:Kenneth R. Jones 更新时间:11/8/2023 访问量:65
使用数据注释的 A-Z、Dash 的正则表达式
Regular Expression for A-Z, Dash using Data Annotations
问:
我需要一个 URL 友好的 slug 的正则表达式,它只能包含小写字母和连字符。它不能以连字符开头或结尾,也不能有多个连续的破折号。
它将在 C# 中的数据注释中使用:
[RegularExpression("", ErrorMessage = "Slug can only contain lowercase letters and dash; must not start or end with a dash; must not have more then 1 consecutive dash.")]
我从这个问题中尝试了以下表达方式。
/^[a-z0-9]+(?:-[a-z0-9]+)*$/
/^[a-z0-9]+(?:[_-][a-z0-9]+)*$/
- 如何修改表达式以验证我需要的内容?
- 有人可以进一步解释在这种情况下非捕获组是如何工作的吗?我不明白我从谷歌那里得到的解释。
C-Sharp (有效) c-sharp-code(有效) -csharp(无效) csharp-(无效) c--sharp(无效) csharp9 (无效) c_sharp(无效)
答:
-1赞
Dai
11/8/2023
#1
用:
^[a-z](?!.*--)[a-z\-]*[a-z]$
演示:https://regex101.com/r/qXNO3y/3
解释:
^ # Anchor at start of string.
[a-z] # The first character must be in the range [a-z].
(?!.*--) # Assert that "--" does not appear anywhere from this point onwards.
[a-z\-]* # Allow any subsequent chars to be in the range [a-z], or be '-' (while never matching "--" due to the assertion prior).
[a-z] # The last character must be in the range [a-z]
$ # Anchor to the end of the string.
用法:
static readonly Regex _slugRegex = new Regex( @"^[a-z](?!.*--)[a-z\-]*[a-z]$", RegexOptions.Compiled );
_slugRegex.IsMatch( "foo-bar" ); // OK
_slugRegex.IsMatch( "foo--bar" ); // Fails
_slugRegex.IsMatch( "foo-bar-" ); // Fails
_slugRegex.IsMatch( "-foo-bar" ); // Fails
评论
0赞
Kenneth R. Jones
11/8/2023
它似乎不起作用,因为它允许数字。
0赞
Dai
11/8/2023
@KennethR.琼斯 哎呀,对不起。现在检查。
0赞
Kenneth R. Jones
11/8/2023
差不多,但它仍然验证“csh-a-rp-”。这应该会失败,因为末尾有一个破折号。
0赞
Dai
11/8/2023
第三次幸运?
0赞
Dai
11/8/2023
@KennethR.琼斯:什么说的?
0赞
Kenneth R. Jones
11/8/2023
#2
此表达式还回答了以下问题:
^[a-z]+(?:-[a-z]+)*$
它满足了我最初需要的所有要求。
评论
+
^[a-z]+(?:-[a-z]+)*$