简体   繁体   English

C#正则表达式,用于x个连字符分隔的AZ组数

[英]C# Regular Expression for x number of groups of A-Z separated by hyphen

I am trying to match the following pattern. 我正在尝试匹配以下模式。

A minimum of 3 'groups' of alphanumeric characters separated by a hyphen. 至少3个“组”的字母数字字符,中间用连字符分隔。

Eg: ABC1-AB-B5-ABC1 例如:ABC1-AB-B5-ABC1

Each group can be any number of characters long. 每个组的长度可以是任意数量的字符。

I have tried the following: 我尝试了以下方法:

^(\w*(-)){3,}?$

This gives me what I want to an extent. 这在一定程度上给了我我想要的东西。

ABC1-AB-B5-0001 fails, and ABC1-AB-B5-0001- passes. ABC1-AB-B5-0001失败,并且ABC1-AB-B5-0001-通过。

I don't want the trailing hyphen to be a requirement. 我不希望尾随连字符成为必需。

I can't figure out how to modify the expression. 我不知道如何修改表达式。

Your ^(\\w*(-)){3,}?$ pattern even allows a string like ----- because the only required pattern here is a hyphen: \\w* may match 0 word chars. 您的^(\\w*(-)){3,}?$模式甚至允许使用-----这样的字符串,因为这里唯一需要的模式是连字符: \\w*可以匹配0个字符。 The - may be both leading and trailing because of that. 因此, -可能同时在前面和后面。

You may use 您可以使用

\A\w+(?:-\w+){2,}\z

Details : 详细资料

  • \\A - start of string \\A字符串开始
  • \\w+ - 1+ word chars (that is, letters, digits or _ symbols) \\w+ -1个以上的字符字符(即字母,数字或_符号)
  • (?:-\\w+){2,} - 2 or more sequences of: (?:-\\w+){2,} -2个或更多序列:
    • - - a single hyphen -单个连字符
    • \\w+ - 1 or more word chars \\w+ -1个或多个字字符
  • \\z - the very end of string. \\z字符串的结尾。

See the regex demo . 参见regex演示

Or, if you do not want to allow _ : 或者,如果您不想允许_

\A[^\W_]+(?:-[^\W_]+){2,}\z

or to only allow ASCII letters and digits: 或仅允许ASCII字母和数字:

\A[A-Za-z0-9]+(?:-[A-Za-z0-9]+){2,}\z

可能是这样的:

^\w+-\w+-\w+(-\w+)*$
^(\w+-){2,}(\w+)-?$

匹配2个以上由连字符分隔的组,然后匹配一个可能由连字符终止的组。

((?:-?\\w+){3,})

Matches minimum 3 groups, optionally starting with a hyphen, thus ignoring the trailing hyphen. 匹配最少3个组,可选地以连字符开头 ,因此忽略尾随的连字符。

Note that the \\w word character also select the underscore char _ as well as 0-9 and az 请注意, \\w字字符还会选择下划线char _以及0-9az

link to demo 链接到演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM