C# 正则表达式替换所有出现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17242416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:56:33  来源:igfitidea点击:

Regex replace all occurrences

c#.net

提问by BrianK

I need to replace a string where it follows a specific string and some varying data. I need to keep the beginning and the middle and just replace the end. When I tried the code below, it replaces only the last occurance. I have tried switching to a non greedy match but then it doesn't find it. The middle could contain new lines as well spaces, letters and numbers.

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

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. " + @"" + " 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.

How do I replace every occurance of "Old ending."

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

采纳答案by Chris

I think Kendall is bang on with the related link, a non greedy matche.g.

我认为 Kendall 正在使用相关链接,一个非贪婪的匹配,例如

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

Should do the trick.

应该做的伎俩。

Edit:

编辑:

You should also be able to change the pattern inside your capture region to be: .*where .will match any character except the newline character.

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

回答by Jason

If all you want to do is replace Old endingwith New ending, why don't you just use good old string.Replace? Will be easier and faster than using regex

如果你想要做的就是更换Old endingNew ending,你为什么不只是使用好老与string.replace?将比使用正则表达式更容易、更快

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

Update:To replace Old endingwherever it is preceded with Begining of story...then use this regex (?<=Beginning of story.*?)Old ending, play around with this if you have slight variations, but this should get you there

更新:要替换Old ending前面的任何地方,Begining of story...然后使用此正则表达式(?<=Beginning of story.*?)Old ending,如果您有细微的变化,请使用此正则表达式,但这应该可以帮助您

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

This basically says, find and replace "Old ending" with "New ending", but only if it starts with "Beginning of story blah blah blah"

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