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

本文关键字:短语 替换 字符串 何使用 正则表达式 | 更新日期: 2023-09-27 18:26:35

我有以下字符串。

*keyName:品牌SLES重新定位:(不可重新定位)*keyOpenEnd

我想用{"重新封装*key,用"重新封装*keyOpenEnd:所以我有一个的结果字符串

{"名称:品牌SLES重新定位:(不可重新定位)":

所以我有

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

我尝试过各种不同的组合,但都不起作用。

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

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

为什么不直接使用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

尝试将^'*key替换为{,将'*keyOpenEnd$替换为}

已编辑,如果*是通配符,则执行以下

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