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

时间:2021-09-01 22:19:07

I have to regex a string whose format should be like

我必须正则表达一个格式应该是的字符串

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

then finally have to match if the regex is valid

如果正则表达式有效,那么最后必须匹配

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

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

I am actually stuck. I am using c# .Looping through the characters an checking the conditions. But this does not look like an ideal solution . Please assist using Regex/C#

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

2 个解决方案

#1


1  

This regex could be expressed as follows

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

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

#2


0  

I assume you need to match the whole string that matches the pattern you defined.

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

Use

使用

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");

If you need to make it Unicode aware, replace all [0-9] with \d and all [a-zA-Z] with \p{L}.

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

Details:

细节:

  • \A - start of string
  • \ A - 字符串的开头
  • [0-9]{2} - 2 digits
  • [0-9] {2} - 2位数
  • [a-zA-Z]{5} - 5 letters
  • [a-zA-Z] {5} - 5个字母
  • [0-9]{4} - 4 digits
  • [0-9] {4} - 4位数
  • [a-zA-Z] - a letter
  • [a-zA-Z] - 一封信
  • [a-zA-Z0-9]{3} - 3 alphanumeric symbols (Unicode aware - [\p{L}\p{N}])
  • [a-zA-Z0-9] {3} - 3个字母数字符号(Unicode识别 - [\ p {L} \ p {N}])
  • \z - the very end of string. If a newline (LF) char follows it and is the last char in the string, the match will fail.
  • \ z - 字符串的结尾。如果新行(LF)字符跟在它后面并且是字符串中的最后一个字符串,则匹配将失败。

#1


1  

This regex could be expressed as follows

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

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

#2


0  

I assume you need to match the whole string that matches the pattern you defined.

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

Use

使用

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");

If you need to make it Unicode aware, replace all [0-9] with \d and all [a-zA-Z] with \p{L}.

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

Details:

细节:

  • \A - start of string
  • \ A - 字符串的开头
  • [0-9]{2} - 2 digits
  • [0-9] {2} - 2位数
  • [a-zA-Z]{5} - 5 letters
  • [a-zA-Z] {5} - 5个字母
  • [0-9]{4} - 4 digits
  • [0-9] {4} - 4位数
  • [a-zA-Z] - a letter
  • [a-zA-Z] - 一封信
  • [a-zA-Z0-9]{3} - 3 alphanumeric symbols (Unicode aware - [\p{L}\p{N}])
  • [a-zA-Z0-9] {3} - 3个字母数字符号(Unicode识别 - [\ p {L} \ p {N}])
  • \z - the very end of string. If a newline (LF) char follows it and is the last char in the string, the match will fail.
  • \ z - 字符串的结尾。如果新行(LF)字符跟在它后面并且是字符串中的最后一个字符串,则匹配将失败。