8

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

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.

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

4

2 回答 2

11

我认为 Kendall 很喜欢相关链接,例如非贪婪匹配

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

应该做的伎俩。

编辑:

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

于 2013-06-21T19:12:00.510 回答
5

如果您只想替换Old endingNew 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");

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

于 2013-06-21T18:56:31.677 回答