Regex之间的替换
本文关键字:替换 之间 Regex | 更新日期: 2023-09-27 18:19:14
我一直在努力理解正则表达式,是否有任何方法我可以替换字符(s)之间的两个字符串/例如我有
sometextREPLACEsomeothertext
我想替换,替换(这可以是任何在实际工作中)只有之间的sometext和someothertext与其他字符串。有谁能帮我一下吗?
编辑假设我的输入字符串是
sometext_REPLACE_someotherText_something_REPLACE_nothing
我想替换sometext和someotherText之间的replace文本产生以下输出
sometext_THISISREPLACED_someotherText_something_REPLACE_nothing
谢谢
如果我正确理解了你的问题,你可能想要使用向前看和向后看你的正则表达式
(?<=...) # matches a positive look behind
(?=...) # matches a positive look ahead
因此,(?<=sometext)('w+?)(?=someothertext)
将匹配任何在'sometext'后面和'someothertext'后面至少有1个字符的'word'
在c#:result = Regex.Replace(subject, @"(?<=sometext)('w+?)(?=someothertext)", "REPLACE");
这是测试字符串是否有效的正则表达式。
'^.REPLACE.'
c#替换string s = "sdfsdfREPLACEdhfsdg";
string v = s.Replace("REPLACE", "SOMETEXT");