实用正则表达式匹配和替换大全(3)

例如,"aabbc11asd", 返回结果为aa bb 11三组match

 
<(?<tag>[^\s>]+)[^>]*>.*</\k<tag>>   匹配成对的HTML标签  
(?!)   不出现,负声明
下例演示如何取得一个<a>标签对中的全部内容,即使其中包含别的HTML tag。

string newsContent = @"url:<a href=""1.html""><img src=""1.gif"">test<spancolor: #006080">"color:red;"">   Regex</span></a>."; Regex regEnd = new Regex(@"<\s*a[^>]*>([^<]|<(?!/a))*<\s*/a\s*>",RegexOptions.Multiline);

 

目的:匹配 关键字="",例如获得关键字keyword,value;获得等于的值abc和test

表达式:string (?<x>[^=]*?) *= *(?<y>[^;]*?);

代码:

private void ParseKeywords(string input) { System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(input, @"string (?<x>[^=]*?) *= *(?<y>[^;]*?);"); if (mc != null && mc.Count > 0) { foreach (System.Text.RegularExpressions.Match m in mc) { string keyword = m.Groups["x"].Value; string value = m.Groups["y"].Value; } } }

截图:

实用正则表达式匹配和替换大全


2. 匹配并替换

输入:public <%=classname%>Extension : IExt

目的:匹配 <%= %>中间的classname并替换

表达式:<%=.*%>

代码:

private string Replace(string input) { return Regex.Replace(input, @"<%=.*%>", new MatchEvaluator(RefineCodeTag), RegexOptions.Singleline); } string RefineCodeTag(Match m) { string x = m.ToString(); x = Regex.Replace(x, "<%=", ""); x = Regex.Replace(x, "%>", ""); return x.Trim() + ","; }

截图:

实用正则表达式匹配和替换大全


正则表达式选项RegexOptions:

ExplicitCapture

  n  

只有定义了命名或编号的组才捕获

 
IgnoreCase   i   不区分大小写  
IgnorePatternWhitespace   x   消除模式中的非转义空白并启用由 # 标记的注释。  
MultiLine   m  

多行模式,其原理是修改了^和$的含义

 
SingleLine   s  

单行模式,和MultiLine相对应

 

正则表达式替换的其他功能:

$number   把匹配的第number组替换成替换表达式

这段代码返回的是 “01 012 03 05”

就是说,对组一的每个匹配结果都用"0$1"这个表达式来替换,"0$1"中"$1"由组1匹配的结果代入


public static void Main() { string s = "1 12 3 5"; s = Regex.Replace(s,@"(\d+)(?#这个是注释)","0$1",RegexOptions.Compiled|RegexOptions.IgnoreCase); Console.WriteLine(s); Console.ReadLine(); }

 

${name}

 

把匹配的组名为"name"的组替换成表达式,

上例的Regex expression改成@"(?<name>\d+)(?#这个是注释)"后面的替换式改为"0${name}"结果是一样的

 

$$

 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjssyp.html