我需要替换一个字符串,它跟在一个特定的字符串和一些不同的数据之后.我需要保持开头和中间,只需更换结束.当我尝试下面的代码时,它只替换最后一次出现.我试过切换到一个非贪婪的比赛,但后来却找不到它.中间可以包含新的行,空格,字母和数字.
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.
Run Code Online (Sandbox Code Playgroud)
如何取代每次出现的"旧结局".
s1 = Regex.Replace(s, @"Beginning of story. ([\s\S]*?) Old ending.", "Beginning of story. " + @"$1" + " New ending.", RegexOptions.Multiline | RegexOptions.IgnoreCase);
Run Code Online (Sandbox Code Playgroud)
应该做的伎俩.
编辑:
您还应该能够将捕获区域内的模式更改为:.*
where .将匹配除换行符之外的任何字符.
如果你想要做的就是更换Old ending用New ending,你为什么不只是使用好老与string.replace?比使用正则表达式更容易,更快捷
String s = "Beginning of story. Keep this sentence. Old ending.\n";
s.Replace("Old ending", "New ending");
Run Code Online (Sandbox Code Playgroud)
更新: 要替换Old ending之前的任何地方,Begining of story...然后使用此正则表达式(?<=Beginning of story.*?)Old ending,如果你有轻微的变化,请玩这个,但这应该让你到那里
Regex.Replace(s, @"(?<=Beginning of story.*?)Old ending", "New ending");
Run Code Online (Sandbox Code Playgroud)
这基本上说,找到并用"新结局"取代"旧结局",但只有当它以"故事的开头等等等等"开头时
| 归档时间: |
|
| 查看次数: |
25622 次 |
| 最近记录: |