2016-12-25 71 views
1

我有话想A 1A 12A 123,为B 1A 1234相同,B 12B 123B 1234其中123我这样做的时候意味着三位 现在:获取完整的单词

MatchCollection ForA1 = Regex.Matches(inFile, @"\b(A [0-9])\b"); 
MatchCollection ForA2 = Regex.Matches(inFile, @"\b(A [0-9][0-9])\b"); 
.... and so on for three and four digits and B; total 8 lines 

减少代码我做到了这一点:

MatchCollection ForAB1 = Regex.Matches(inFile, @"\b(A [0-9]|B [0-9])\b"); 
MatchCollection ForAB2 = Regex.Matches(inFile, @"\b(A [0-9][0-9]|B [0-9][0-9])\b"); 
.... and so on for three and four digits; total 4 lines 

现在,我想这样做:

MatchCollection ForAB1234 = Regex.Matches(inFile, @"\b(A [0-9]|B [0-9]... 
|A [0-9][0-9]|B [0-9][0-9] and so on for three and four digits)\b"); total 1 line 

此时比赛后我这样做:

foreach (Match m in ForAB1) 
    { 
    //many calculations on the basis of index and length etc 
    } 

我想要什么:

foreach (Match m in ForAB1) 
    { 
    if(Match is 'A [0-9]') 
    {//many calculations on the basis of index and length etc} 
    else... 
    } 

还有什么事很简单,让我不必简单地重复代码由于不同的数字位数?我正在寻找我管道的所有不同的比赛。

编辑:真正的问题是,我不希望m.len,然后检查它是否是A或B因为在现实中我有超过30个这样的表情

+1

没有违法,但如果你有-1这个问题应该有,适当的理由,我想你可以在这里写 –

回答

2

为了确保您只检查A 1类型和不A 11类型,你需要使用类似

foreach (Match m in ForAB1) 
{ 
    if (Regex.IsMatch(m.Value, @"^A [0-9]$")) 
    {//many calculations on the basis of index and length etc} 
    else if (Regex.IsMatch(m.Value, @"^A [0-9]{2}$")) 
    {//many calculations on the basis of index and length etc} 
    else... 
} 
+0

纪录都没有问题,我已经有MatchCollection可以查找许多情况尽可能的。我正在寻找我管理的所有不同的匹配 –

+0

那么你为什么使用'\ b'?我猜你正在寻找'^'/'$'锚点,比如'@“^(A [0-9] | B [0-9] ... | A [0-9] [0-9] | B [0-9] [0-9]等三位和四位数字)$“' –

+0

'\ b'不是一个问题匹配不起作用。问题在'foreach'循环里面我想做一件事,如果匹配是A 1,另一个是A 11,它就像'(type1 | type2)'是在正则表达式中,现在我想在MatchCollection中看到如果选择了一个type1或type2 –