【.NET】正则表达式笔记(持续更新)
前言:
正则应用在做判断、截取、过滤有很好的效果,记录一下使用过的方法,能给程序带来很大的方便。
组合1 (.*?)
//style所有属性替换成指定 string regtxt = "style=\"(.*?)\""; Regex reg = new Regex(regtxt, RegexOptions.IgnoreCase); string xhtml2 = reg.Replace(xhtml, "style=\"width:95%;margin:10px;\""); Content = Content.Replace(xhtml, xhtml2);
组合2 (?<=)
string input = "<div><img src=\"123123.jpg\" /></div>"; string pattern = @"(?<=<img(.*)src="").*?(?="")"; foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine(match.Value);
//检查1种异常html标签
//格式:<div style="font-size:16px;"font-size:16px;"="">MBBBBBB</div> string regtxt2 = "\"[^\"]+\"=\""; System.Text.RegularExpressions.Regex reg2 = new System.Text.RegularExpressions.Regex(regtxt2,System.Text.RegularExpressions.RegexOptions.IgnoreCase); txtFile = reg2.Replace(txtFile,"");