正则表达式替换所有出现的事件

时间:2013-06-21 18:53:49

标签: c# .net

我需要替换一个字符串,它跟在一个特定的字符串和一些不同的数据之后。我需要保持开头和中间,只需更换结束。当我尝试下面的代码时,它只替换最后一次出现。我试过切换到一个非贪婪的比赛,但后来却找不到它。中间可以包含新的行,空格,字母和数字。

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.

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

2 个答案:

答案 0 :(得分:9)

我认为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);

应该做的伎俩。

编辑:

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

答案 1 :(得分:6)

如果您只想将Old ending替换为New 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");

这基本上是说,用“新结局”找到并取代“旧结局”,但只有当它以“故事的开头等等等等”开始时才会出现