从MatchCollection C#not group获取完整单词
我有词假设从MatchCollection C#not group获取完整单词,c#,regex,match,C#,Regex,Match,我有词假设a1,a12,a123,a1234,b12,b123,b1234,其中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; tota
a1
,a12
,a123
,a1234
,b12
,b123
,b1234
,其中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
foreach (Match m in ForAB1)
{
//many calculations on the basis of index and length etc
}
为了减少代码,我这样做:
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
在比赛结束后的这个时候,我会这样做:
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
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,因为实际上我有三十多个这样的表达式要确保只检查
A1
类型而不是A11
类型,需要使用
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...
}
事件不是问题,我已经有了MatchCollection,它可以查找尽可能多的事件。我正在查找我传输的所有不同匹配项。为什么要使用
\b
?我猜你正在寻找^
/$
锚,比如@^(A[0-9]| B[0-9]…| A[0-9][0-9]| B[0-9][0-9]等等,三位数和四位数)$”
\B
不是问题,匹配确实有效。问题是在foreach
循环中,如果匹配是1,我想做一件事,如果匹配是11,我想做另一件事,这就像(type1 | type2)
在regex中,现在我想在MatchCollection中看到选择的是type1还是type2So,用^
和$
封装这些模式有效吗?有什么不同?没有冒犯,但如果你有-1这个问题,应该有适当的理由,我想你可以在这里写