我认为A 1
,A 12
,A 123
,A 1234
和B 1
,B 12
,B 123
相同,B 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个这样的表达
答案 0 :(得分: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...
}