程序代码使用正则表达式如何修改匹配到的值:
代码一:
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string input = "1851 1999 1950 1905 2003"; string pattern = @"(?<=19)d{2}"; //(w+)(s)(w+) $3$2$1 "one two" input="one two"; pattern=@"(w+)(s)(w+)"; Console.WriteLine(Regex.Replace(input,pattern,"1.$3 $2 2.$1", RegexOptions.Compiled | RegexOptions.IgnoreCase)); foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine(match.Value);
//(?< word1>w+)(s)(?< word2>w+) ${word2} ${word1} "one two" input="one two"; pattern=@"(?<word1>w+)(s)(?<word2>w+)"; Console.WriteLine(Regex.Replace(input,pattern,"${word2} ${word1}", RegexOptions.Compiled | RegexOptions.IgnoreCase)); foreach (Match match in Regex.Matches(input, pattern)) Console.WriteLine(match.Value); } }
代码二:
using System; using System.Text.RegularExpressions; namespace RegExApplication { class Program { static void Main(string[] args) { string s = "<img aa=bb cc=dd src="img1111.jpg" />变成 <img src="http://aaa/bbbcca.jpg" /><img alt="hello" src="222.jpg" /><img src="http://www.w3dev.cn/logo.jpg" />"; Console.WriteLine(s); Console.WriteLine("****************************"); s = Regex.Replace(s, "(<img[\s\S]+?)src=(["'])(?!(https?://))([^"']+)", "$1src=$2http://aaaa/$4", RegexOptions.Compiled | RegexOptions.IgnoreCase); Console.WriteLine( s ); } }