2024年3月26日发(作者:)

C#正则表达式匹配字符串的方法如下:

1.使用C#中使用正则表达式rExpressions命名空间;

2.使用C#中使用正则表达式Matches()方法匹配字符串,格式如下:

MatchCollection Matches = s(Str, Pattern, C

ase | itCapture);

其中Str表示输入字符串,Pattern表示匹配模式,Case表示

忽略大小写,itCapture表示改变收集匹配方式。

3.匹配结果保存在MatchCollection集合中,可以通过循环遍历结果集取出Match

对象的结果。

:

1.

2.

3.

4.

5.

6.

7.

8.

9.

using System;

using rExpressions;

namespace s

{

public class TestRegular

{

public static void WriteMatches(string str, Match

Collection matches)

{

;

11. ine("No. of matches : " +

);

12. foreach (Match nextMatch in matches)

13. {

14. //取出匹配字符串和最多10个外围字符

15. int Index = ;

16. string result = ng(

);

17. int charsBefore = (Index < 5) ?

Index : 5;

18. int fromEnd = - Index

- ;

19. int charsAfter = (fromEnd < 5) ?

fromEnd : 5;

10. ine("nString is : " + str)

20. int charsToDisplay = charsBefore +

+ charsAfter;

21.

22. ine("Index: {0},tStrin

g: {1},t{2}", Index, result, ing(Index - charsBefore,

charsToDisplay));

23. }

24. }

25.

26. public static void Main()

27. {

28. string Str = @"My name is Magci, for s

hort mgc. I like c sharp!";

29.

30. //查找“gc”

31. string Pattern = "gc";

32. MatchCollection Matches = s(Str

, Pattern, Case | itCapture);

33.

34. WriteMatches(Str, Matches);

35.

36. //查找以“m”开头,“c”结尾的单词

37. Pattern = @"bmS*cb";

38. Matches = s(Str, Pattern, Rege

Case | itCapture);

39.

40. WriteMatches(Str, Matches);

41. }