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