参见英文答案 >
My regex is matching too much. How do I make it stop?5个
我需要替换一个字符串,它遵循一个特定的字符串和一些不同的数据.我需要保持开头和中间,只需更换结束.当我尝试下面的代码时,它只替换最后一次出现.我试过切换到非贪婪的比赛,但后来却找不到它.中间可以包含新的行,空格,字母和数字.
我需要替换一个字符串,它遵循一个特定的字符串和一些不同的数据.我需要保持开头和中间,只需更换结束.当我尝试下面的代码时,它只替换最后一次出现.我试过切换到非贪婪的比赛,但后来却找不到它.中间可以包含新的行,空格,字母和数字.
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.
如何更换“旧结局”的每一次出现.
解决方法
我认为Kendall正在使用相关链接
a non greedy match,例如
s1 = Regex.Replace(s,@"Beginning of story. ([\s\S]*?) Old ending.",RegexOptions.Multiline | RegexOptions.IgnoreCase);
应该做的伎俩.
编辑:
您还应该能够将捕获区域内的模式更改为:.*在哪里将匹配除换行符之外的任何字符.