1. 程式人生 > >使用正則表達式替換字符串

使用正則表達式替換字符串

alt result message pre () 方法 搜索 tex csharp

實現效果:

  技術分享圖片

知識運用:

  Regex類的Replace()方法:用於替換在指定字符串內匹配正則式的字符串為某字符串

  public static string Replace(string input,string pattern,string replacement)

  input   要搜索匹配項的字符串

  pattern    要匹配的正則表達式模式

  replacement    要替換的為結果的字符串

實現代碼:

        private void button1_Click(object sender, EventArgs e)
        {
            string result = System.Text.RegularExpressions.
                Regex.Replace(textBox1.Text,"[A-Za-z]+",textBox2.Text);
            MessageBox.Show("原字符串:\n"+textBox1.Text+"\n"+
                    "替換為:\n"+textBox2.Text+"\n"+"替換後:\n"+result);
        }

使用正則表達式替換字符串