使用数据注释的 A-Z、Dash 的正则表达式

Regular Expression for A-Z, Dash using Data Annotations

提问人:Kenneth R. Jones 提问时间:11/8/2023 最后编辑:Kenneth R. Jones 更新时间:11/8/2023 访问量:65

问:

我需要一个 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]+)*$/
  1. 如何修改表达式以验证我需要的内容?
  2. 有人可以进一步解释在这种情况下非捕获组是如何工作的吗?我不明白我从谷歌那里得到的解释。

C-Sharp (有效) c-sharp-code(有效) -csharp(无效) csharp-(无效) c--sharp(无效) csharp9 (无效) c_sharp(无效)

C# 正则表达式 数据批注

评论

0赞 Dai 11/8/2023
非捕获组是因为您也需要一个组来附加量词 (),但又没有普通捕获的代价。+
0赞 Dai 11/8/2023
...但就您的需求而言,您不需要任何非捕获组(或根本不需要任何组)。
0赞 Dai 11/8/2023
提示:使用 Regex101.com 获取正则表达式方面的帮助。
0赞 The fourth bird 11/8/2023
我想你的意思是这样没有匹配的数字,对吧? regex101.com/r/a05kLh/1^[a-z]+(?:-[a-z]+)*$
0赞 Kenneth R. Jones 11/8/2023
@Dai如果没有那个非捕获组,我无法让它工作。如果我删除它,它似乎不再检查连续的连字符。

答:

-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]+)*$

它满足了我最初需要的所有要求。