使用正则表达式C#替换字符串中的单词

时间:2018-08-23 06:27:27

标签: c# regex string

return 0

我想用string sentence = "My current address is #6789, Baker Avenue (CB)". 代替#6789, Baker Avenue (

正则表达式为#574, Tomson Street (

如何在C#中执行此操作?

2 个答案:

答案 0 :(得分:2)

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string address = "My current address is #6789, Baker Avenue (CB)";
        Regex regex = new Regex("#.+\\(");
        address = regex.Replace(address, "#574, Tomson Street (");
        Console.WriteLine(address);
    }
}

您需要退出开口支架。同样在c#\中必须转义字符,因此我们需要组合\\( 我从您的提案中删除了^和$。这些字符将模式锚定到短语的开头和结尾。事实并非如此。

答案 1 :(得分:1)

尝试一下:

string sentence = "My current address is #6789, Baker Avenue (CB)";

var result = Regex.Replace(sentence, @"#\d+,[^(]+", "#574, Tomson Street ");

模式为#\d+,[^(]+

这是一个哈希#,后跟至少一个数字\d+,逗号和至少一个不加括号的字符:[^(]+