C# 如何计算列表c中匹配正则表达式的列表#
我有一个列表,我想使用正则表达式在包含文本1到文本100的列表中计数 我创建了shows count=0。我似乎在这里找不到我的错误C# 如何计算列表c中匹配正则表达式的列表#,c#,regex,C#,Regex,我有一个列表,我想使用正则表达式在包含文本1到文本100的列表中计数 我创建了shows count=0。我似乎在这里找不到我的错误 using System; using System.Text.RegularExpressions; using System.Collections.Generic; public class Program { public static void Main() { // Text 1
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Text 1 to Text 100
Regex reg = new Regex(@"Text + /^(?:100|[1-9]?[0-9])$");
int count = 0;
// Expected to count 3
List<string> myTexts = new List<string>() {"Text 1", "Text 2", "Text 3", "Text 500"};
foreach (var myText in myTexts)
{
if(reg.IsMatch(myText))
count++;
}
Console.WriteLine($"There are {count} matches in the list");
}
}
使用系统;
使用System.Text.RegularExpressions;
使用System.Collections.Generic;
公共课程
{
公共静态void Main()
{
//文本1至文本100
正则表达式reg=新正则表达式(@“Text+/^(?:100|[1-9]?[0-9])$);
整数计数=0;
//预计数到3
List myTexts=新列表(){“文本1”、“文本2”、“文本3”、“文本500”};
foreach(myText中的var myText)
{
如果(注册IsMatch(myText))
计数++;
}
WriteLine($“列表中有{count}个匹配项”);
}
}
只需对正则表达式稍作更改(删除不必要的“/^”
部分),就可以使用一点System.Linq
来获取匹配计数:
Regex reg = new Regex(@"Text +(?:100|[1-9]?[0-9])$");
// Expected to count 3
var myTexts = new List<string> {"Text 1", "Text 2", "Text 3", "Text 500"};
var count = myTexts.Count(text => reg.IsMatch(text));
// count == 3
Regex reg=newregex(@“Text+(?:100 |[1-9]?[0-9])$);
//预计数到3
var mytext=新列表{“文本1”、“文本2”、“文本3”、“文本500”};
var count=mytext.count(text=>reg.IsMatch(text));
//计数==3
<代码> >为什么你在正则表达式的中间放置<代码> /^ < /代码>?此外,空间也是有意义的。请参见,您需要@“Text+(?:100|[1-9]?[0-9])$”
这是否回答了您的问题?