【问题标题】:Regex replace all occurrences [duplicate]正则表达式替换所有出现[重复]
【发布时间】:2013-06-19 00:12:09
【问题描述】:

我需要替换一个字符串,它跟在一个特定的字符串和一些不同的数据之后。我需要保留开头和中间,只替换结尾。当我尝试下面的代码时,它只替换最后一次出现。我尝试切换到非贪婪匹配,但没有找到它。中间可以包含新行以及空格、字母和数字。

String s = "Beginning of story. Keep this sentence. Old ending.\n";
s += s;
s += s;
s1 = Regex.Replace(s, @"Beginning of story. ([\s\S]*) Old ending.", "Beginning of story. " + @"$1" + " New ending.", RegexOptions.Multiline | RegexOptions.IgnoreCase);

The result is this:
Beginning of story. Keep this sentence. Old ending.
Beginning of story. Keep this sentence. Old ending.
Beginning of story. Keep this sentence. Old ending.
Beginning of story. Keep this sentence. New ending.

如何替换每次出现的“旧结局”。

【问题讨论】:

  • 尝试在模式的末尾添加一个$ - 应该匹配每一行的末尾,给定您的Multiline 选项。
  • 非贪婪匹配应该处理它。您能展示一下您的尝试吗?
  • 我试过这个。它不会替换任何东西 s1 = Regex.Replace(s, @"故事开始。([\s\S]?) 旧结局。", "故事开始。" + @"$1" + " 新结局。 ", RegexOptions.Multiline | RegexOptions.IgnoreCase);
  • @BrianK:我认为非贪婪匹配将是 *?,而不仅仅是 ? - ? 本身是 0 or 1

标签: c# .net


【解决方案1】:

我认为 Kendall 很喜欢相关链接,a non greedy match 例如

s1 = Regex.Replace(s, @"Beginning of story. ([\s\S]*?) Old ending.", "Beginning of story. " + @"$1" + " New ending.", RegexOptions.Multiline | RegexOptions.IgnoreCase);

应该做的伎俩。

编辑:

您还应该能够将捕获区域内的模式更改为:.* 其中. 将匹配除换行符以外的任何字符。

【讨论】:

    【解决方案2】:

    如果您只想用New ending 替换Old ending,为什么不直接使用旧的string.Replace?会比使用正则表达式更容易和更快

    String s = "Beginning of story. Keep this sentence. Old ending.\n";
    s.Replace("Old ending", "New ending");
    

    更新:要将Old ending 替换为Begining of story...,然后使用此正则表达式(?<=Beginning of story.*?)Old ending,如果您有细微的变化,请尝试一下,但这应该可以让您到达那里

    Regex.Replace(s, @"(?<=Beginning of story.*?)Old ending", "New ending");
    

    这基本上是说,找到“旧结局”并将其替换为“新结局”,但前提是它以“故事开头等等等等”开头

    【讨论】:

    • 我只想替换出现在“故事开始”之后的“旧结局”。如果它发生在该模式之外,我不想替换它。
    • @BrianK 查看更新的答案,我提供的模式应该可以解决问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多