如何在特定模式中正则表达长度为15的字符串

时间:2017-05-26 10:00:51

标签: c# regex

我必须正则表达一个格式应该像

的字符串
Position  Format
1st       Numeric
2nd       Numeric
3rd       Alphabet
4th       Alphabet
5th       Alphabet
6th       Alphabet
7th       Alphabet
8th       Numeric
9th       Numeric
10th      Numeric
11th      Numeric
12th      Alphabet
13th      AlphaNumeric
14th      AlphaNumeric
15th      AlphaNumeric

然后如果正则表达式有效则最终必须匹配

Match match = Regex.Match( inputString, regex, RegexOptions.IgnoreCase );

if ( inputString != string.Empty && match.Success )
{
     // Condition
}

我实际上被卡住了。我正在使用c#。通过字符检查条件。但这看起来不是一个理想的解决方案。 请协助使用Regex / C#

2 个答案:

答案 0 :(得分:1)

这个正则表达式可以表示如下

\d{2}[a-zA-Z]{5}\d{4}[a-zA-Z][\da-zA-Z]{3}

答案 1 :(得分:0)

我假设您需要匹配与您定义的模式匹配的整个字符串。

使用

var isValid = Regex.IsMatch(s, @"\A[0-9]{2}[a-zA-Z]{5}[0-9]{4}[a-zA-Z][a-zA-Z0-9]{3}\z");

如果您需要识别Unicode,请将所有[0-9]替换为\d,将所有[a-zA-Z]替换为\p{L}

<强>详情:

  • \A - 字符串开头
  • [0-9]{2} - 2位数
  • [a-zA-Z]{5} - 5个字母
  • [0-9]{4} - 4位数
  • [a-zA-Z] - 一封信
  • [a-zA-Z0-9]{3} - 3个字母数字符号(Unicode识别 - [\p{L}\p{N}]
  • \z - 字符串的结尾。如果新行(LF)字符跟在它后面并且是字符串中的最后一个字符串,则匹配将失败。