加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 正则表达式替换所有出现次数

发布时间:2020-12-15 08:06:13 所属栏目:百科 来源:网络整理
导读:参见英文答案 My regex is matching too much. How do I make it stop?5个 我需要替换一个字符串,它遵循一个特定的字符串和一些不同的数据.我需要保持开头和中间,只需更换结束.当我尝试下面的代码时,它只替换最后一次出现.我试过切换到非贪婪的比赛,但后来却
参见英文答案 > 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. ([sS]*) 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. ([sS]*?) Old ending.",RegexOptions.Multiline | RegexOptions.IgnoreCase);

应该做的伎俩.

编辑:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读