意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

在C#中,可以使用Regex类来匹配多个字符串

来源:恒创科技 编辑:恒创科技编辑部
2024-02-06 13:48:20

在C#中,可以使用Regex类来匹配多个字符串。下面是一个示例代码:

usingSystem; usingSystem.Text.RegularExpressions; classProgram { staticvoidMain() { stringinput="Helloworld!Thisisatest."; string[]keywords={"Hello","world","test"}; foreach(stringkeywordinkeywords) { //使用Regex类的静态方法Match来进行匹配 Matchmatch=Regex.Match(input,keyword); if(match.Success) { Console.WriteLine("Found'{0}'atposition{1}.",keyword,match.Index); } else { Console.WriteLine("'{0}'notfound.",keyword); } } } }

输出结果将会是:

Found'Hello'atposition0. Found'world'atposition6. Found'test'atposition21.

在上面的示例中,我们定义了一个字符串数组keywords,并通过循环,使用Regex.Match方法来在输入字符串input中逐个匹配关键字。如果找到了匹配项,就会输出关键字的位置;否则,输出notfound




在C#中,可以使用Regex类来匹配多个字符串

上一篇: xshell怎么连接云服务器? 下一篇: 要定义一个类变量,可以在类的内部直接赋值给一个变量,例如: classMyClass: class_variable=10 要使用类变量,可以通过类名或实例对象来访问它,例如: print(MyClass.class_variable)#输出:10 my_object=MyClass() print(my_object.class_variable