正则表达式如何替换指定标签里的内容?
在html页里,我自定义了一个标签JSContainer(不区分大小写),可以出现多个这样的标签,我想问如何把
<JSContainer>
<script src="Assets/Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="Assets/Scripts/jquery.validate-vsdoc.js" type="text/javascript"></script>
</JSContainer>
换成
<JSContainer>
<script src='/Assets/Scripts/js.axd?files=jquery.validate.js,jquery.validate-vsdoc.js' type='text/javascript' ></script>
</JSContainer>?或者不用正则表达式也行,但JSContainer不区分大小写,只要能够达到此效果并且效率不能太差。
[解决办法]
StreamReader reader = new StreamReader("c:\\temp\\1.txt",Encoding.Default); string source = reader.ReadToEnd(); Regex reg = new Regex(@"(?is)(?<=<JSContainer>).*?(?=</JSContainer>)"); Match mm = reg.Match(source); source = reg.Replace(source, "<script src='/Assets/Scripts/js.axd?files=jquery.validate.js,jquery.validate-vsdoc.js' type='text/javascript' ></script>");
[解决办法]
string str = @"<JSContainer><script src=""Assets/Scripts/jquery.validate.js"" type=""text/javascript""></script><script src=""Assets/Scripts/jquery.validate-vsdoc.js"" type=""text/javascript""></script></JSContainer>"; Regex reg = new Regex(@"(?is)<JSContainer>(?:\s*<script\ssrc="".*?/([^""/]+?)"".*?</script>)*\s*</JSContainer>"); Match m = reg.Match(str); string result = "<JSContainer><script src='/Assets/Scripts/js.axd?files="; foreach (Capture c in m.Groups[1].Captures) result += c.Value + ","; result = result.TrimEnd(',') + "\" type=\"text/javascript\"></script>"; Console.WriteLine(reg.Replace(str, result));