2011-12-08 43 views
1

我必须写一个函数,将得到一个字符串,这将有2种形式:C#正则表达式分组

  1. XX..X,YY..Y其中XX..X是最多4个字符,YY..Y是最多26个字符(X和Y是数字或A或B)
  2. XX..X其中XX..X是最多8个字符(X是数字或A或B)

例如12A,784B52或4453AB

如何使用正则表达式分组来匹配此行为?

谢谢。

p.s.如果这是遗憾的本地化

+2

你应该提供一些有效的和不是什么的实际例子 – musefan

回答

3

您可以使用一个名为捕获此:

Regex regexObj = new Regex(
    @"\b     # Match a word boundary 
    (?:     # Either match 
    (?<X>[AB\d]{1,4}) # 1-4 characters --> group X 
    ,     # comma 
    (?<Y>[AB\d]{1,26}) # 1-26 characters --> group Y 
    |     # or 
    (?<X>[AB\d]{1,8}) # 1-8 characters --> group X 
    )     # End of alternation 
    \b     # Match a word boundary", 
    RegexOptions.IgnorePatternWhitespace); 
X = regexObj.Match(subjectString).Groups["X"].Value; 
Y = regexObj.Match(subjectString).Groups["Y"].Value; 

我不知道有没有Y组发生了什么,也许你可能需要包装的最后一行在if声明。