Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式替换所有事件_C#_.net - Fatal编程技术网

C# 正则表达式替换所有事件

C# 正则表达式替换所有事件,c#,.net,C#,.net,我需要替换一个字符串,它跟在一个特定的字符串和一些变化的数据后面。我需要保留开头和中间,只需要替换结尾。当我尝试下面的代码时,它只替换最后一次出现的代码。我试着切换到一个非贪婪的匹配,但它没有找到它。中间可以包含新行以及空格、字母和数字 String s = "Beginning of story. Keep this sentence. Old ending.\n"; s += s; s += s; s1 = Regex.Replace(s, @"Beginning of story. ([\

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

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.

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

如果您只想将
旧结尾
替换为
新结尾
,为什么不使用好的旧字符串。替换?将比使用正则表达式更简单、更快

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

更新:若要替换
旧的结尾
,只要前面有
故事的开头…
就使用这个正则表达式
(?我认为Kendall正在使用相关链接,例如

我们应该做到这一点

编辑:

您还应该能够将捕获区域内的模式更改为:
*

其中,
将匹配除换行符以外的任何字符。

尝试在模式末尾添加一个
$
-应该匹配每行的结尾,考虑到您的
多行
选项。相关:非贪婪匹配应该解决它。您可以显示您尝试过的内容吗?我尝试过了。它不会替换任何s1=Regex.Replace(s,@“故事的开始([\s\s]?)旧的结尾。”,“故事的开始”。++“$1”+“新的结尾。”,RegexOptions.Multiline | RegexOptions.IgnoreCase);@BrianK:我认为非贪婪匹配应该是
*?
,而不仅仅是
-
本身就是
0或
。我只想替换“旧的结尾”它发生在“故事开始”之后。如果它发生在该模式之外,我不想替换它。@BrianK请参阅更新的答案,我提供的模式应该会起作用
Regex.Replace(s, @"(?<=Beginning of story.*?)Old ending", "New ending");
s1 = Regex.Replace(s, @"Beginning of story. ([\s\S]*?) Old ending.", "Beginning of story. " + @"$1" + " New ending.", RegexOptions.Multiline | RegexOptions.IgnoreCase);