字符串替换为模式匹配

时间:2014-01-31 17:09:36

标签: c# regex string replace

我从数据库中提取了以下变量字符串并且每次都更改:

例如,我的第一次字符串是:

  

您可以使用[xyz]框架开发[123],网络和[abc]应用

第二次我的字符串是:

  

您可以使用[aaa]框架开发[bbb],网络和[ccc]应用

我想替换

  • [xyz]或[aaa]与.NET

  • [123]或[bbb]与desktop

  • [abc]或[ccc]与mobile

大括号中的文本将会更改,因为它是一个变量字符串,但我想用.NET替换第一个大括号中的文本,用desktop替换第二个大括号中的文本和第三个大括号中的文本mobile

转换后的字符串应为 -

  

您可以使用.NET Framework开发桌面,Web和移动应用程序:

在C#中使用字符串替换最简单的方法是什么?

5 个答案:

答案 0 :(得分:2)

改为使用String.Format

var firstString = ".Net";
var secondString = "desktop";
var thirdString = "mobile";
var originalString = "You can use the {0} Framework to develop {1}, web, and {2} apps";
var newString = string.format(originalString, firstString,secondString,thirdString);

答案 1 :(得分:1)

你可以这样做:

// established sometime earlier
string firstPlaceholder = "[xyz]";
string secondPlaceholder = "[123]";
string thirdPlaceholder = "[abc]";

// then when you need to do the replacement
string result = originalString.Replace(firstPlaceholder, ".NET")
                              .Replace(secondPlaceholder, "desktop")
                              .Replace(thirdPlaceholder, "mobile");

答案 2 :(得分:1)

您可以使用正则表达式执行所需操作:

// Error checking needed.....
string input = "You can use the [xyz] Framework to develop [123], web, and [abc] apps";
Regex re = new Regex(@"(\[[^\]]+\])");
MatchCollection matches = re.Matches(input);
input = input.Replace(matches[0].Value, ".NET").Replace(matches[1].Value, "desktop").Replace(matches[2].Value, "mobile");

答案 3 :(得分:1)

虽然这个答案似乎有点晚了

string input = "You can use the [xyz] Framework to develop [123], web, and [abc] apps";
var pairs = new Dictionary<string, string>()
{
    {"xyz",".NET"},
    {"123","desktop"},
    {"abc","mobile"},
};

var output = Regex.Replace(input, @"\[(.+?)\]", m => pairs[m.Groups[1].Value]);

<强>输出:

You can use the .NET Framework to develop desktop, web, and mobile apps

答案 4 :(得分:0)

结合我的和Jonny Mopp的回答:

        Regex reg = new Regex(@"(\[[^\]]+\])");

        string origString = "You can [xyz] blah blah [abc]";

        var coll = reg.Matches(origString);

        for(int i=0;i<coll.Count; i++)
        {
            origString = origString.Replace(coll[i].Value,"{"+i+"}");
        }

        var newString = string.Format(origString,".Net","desktop");