如何使用正则表达式用字符串替换精确短语

时间:2014-10-15 18:26:32

标签: c# regex string

我有以下字符串。

  

* keyName:branding-SLES重定位:(不可重定位)* keyOpenEnd

我想用{“和* keyOpenEnd with”重新使用*键:所以我有一个结果字符串

  

{“名称:品牌-SLES重定位:(不可重定位)”:

所以我有

output = Regex.Replace(output, @"\b"+"key"+@"\b", "{\"");
output = Regex.Replace(output, @"\b\*keyOpenEnd\b", "\":");

我尝试了各种差异组合,但没有任何效果。

更新:似乎有点混乱。 澄清;我需要替换精确的短语,否则它将取代KeyOpenEnd中的'Key'以及Key,这是不好的。我需要更换短语。

2 个答案:

答案 0 :(得分:1)

为什么不使用string.Replace并确保首先替换更具体的值

output = output.Replace("*keyOpenEnd", "\":").Replace("*key", "{\"");

修改

此处的测试代码用于比较正则表达式时间与string.Replace和我的结果

string s = "*keyName:branding-SLES Relocations:(not relocatable)*keyOpenEnd";
string desired = "{\"Name:branding-SLES Relocations:(not relocatable)\":";

Stopwatch watch = new Stopwatch();

watch.Start();
for (int i = 0; i < 100000; i++)
{
    var n = Regex.Replace(s, @"\*keyOpenEnd", "\":");
    n = Regex.Replace(n, @"\*key", "{\"");
    Assert.AreEqual(desired, n);
}
watch.Stop();

Console.WriteLine("RegEx Total: {0}", watch.Elapsed);

watch.Reset();
watch.Start();
for (int i = 0; i < 100000; i++)
{
    var n = s.Replace("*keyOpenEnd", "\":").Replace("*key", "{\"");
    Assert.AreEqual(desired, n);
}
watch.Stop();

Console.WriteLine("String Replace Total: {0}", watch.Elapsed);

结果:

RegEx Total: 00:00:00.1742555
String Replace Total: 00:00:00.0385957

其他修改

如果你使用一个正则表达式并预先编译使用,string.Replace仍然更快

string s = "*keyName:branding-SLES Relocations:(not relocatable)*keyOpenEnd";
string desired = "{\"Name:branding-SLES Relocations:(not relocatable)\":";
Regex r = new Regex(@"\*key(.*)\*keyOpenEnd", RegexOptions.Compiled);

Stopwatch watch = new Stopwatch();

watch.Start();
for (int i = 0; i < 100000; i++)
{
    var n = r.Replace(s, "{\"$1\":");
    Assert.AreEqual(desired, n);
}
watch.Stop();

Console.WriteLine("RegEx Total: {0}", watch.Elapsed);

watch.Reset();
watch.Start();
for (int i = 0; i < 100000; i++)
{
    var n = s.Replace("*keyOpenEnd", "\":").Replace("*key", "{\"");
    Assert.AreEqual(desired, n);
}
watch.Stop();

Console.WriteLine("String Replace Total: {0}", watch.Elapsed);

结果:

RegEx Total: 00:00:00.0960996
String Replace Total: 00:00:00.0393491

答案 1 :(得分:0)

尝试使用{和^\*key with}

替换\*keyOpenEnd$

编辑,如果*是外卡,请执行以下操作

key(.*)keyOpenEnd替换为{"$1"