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

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

我需要一个 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(有效) c-sharp-代码(有效) -csharp(无效) csharp-(无效) c--升号(无效) csharp9(无效) c_sharp(无效)

c# regex data-annotations
1个回答
0
投票

用途:

^[a-z](?!.*--)[a-z\-]*$

演示:https://regex101.com/r/qXNO3y/2

说明:

^             # 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).
$             # Anchor to the end of the string.

用途:

static readonly Regex _slugRegex = new Regex( @"^[a-z](?!.*--)[a-z\-]*$", RegexOptions.Compiled );

_slugRegex.Matches( "foo-bar" ).Dump(); // OK

_slugRegex.Matches( "foo--bar" ).Dump(); // Fails
© www.soinside.com 2019 - 2024. All rights reserved.