程序代码使用正则表达式如何修改匹配到的值:

代码一:

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}";
        //\b(\w+)(\s)(\w+)\b    $3$2$1    "one two" 
        input="one two";
        pattern=@"\b(\w+)(\s)(\w+)\b";
        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);
//\b(?< word1>\w+)(\s)(?< word2>\w+)\b ${word2} ${word1} "one two" input="one two"; pattern=@"\b(?<word1>\w+)(\s)(?<word2>\w+)\b"; 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=\"\img\1\111.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 );
      }
   }

 

posted on 2018-06-01 17:48  踏歌&而行  阅读(338)  评论(0编辑  收藏  举报