如何用正则表达式移除含动态内容的无占位符目标字符串
如何用正则表达式替换含动态内容的特定格式字符串
看起来你之前的正则方向完全偏了——你用了匹配数字和百分号的规则,但你的目标是匹配地名和邮箱,当然找不到要替换的内容啦!
咱们先拆解一下你要移除的字符串结构:
Are you interested in a holiday in
, then contact .
这里的核心是:
- 固定前缀:
Are you interested in a holiday in(注意开头的空格) - 动态的
:直到后面的逗号为止,所以可以用 [^,]+来匹配任意非逗号的字符(至少一个) - 固定中间部分:
, then contact - 动态的
:直到后面的句号为止,用 [^.]+匹配任意非句号的字符(至少一个) - 固定结尾:
.
所以正确的正则模式应该是:
Are you interested in a holiday in [^,]+, then contact [^.]+.
完整代码示例(C#)
using System.Text.RegularExpressions; string[] originalTexts = { "Hello there. Are you interested in a holiday in New York, then contact nyc@mydomain.com. Let us help you.", "Hey mr! Are you interested in a holiday in LA, then contact la@mydomain.com. We got you!", "Welcome to our humbo home. Are you interested in a holiday in France, then contact france@mydomain.com. See you soon!" }; // 用@前缀避免转义字符的麻烦 string replacePattern = @" Are you interested in a holiday in [^,]+, then contact [^.]+."; foreach (string text in originalTexts) { string cleanedText = Regex.Replace(text, replacePattern, ""); Console.WriteLine(cleanedText); }
运行这段代码后,就能得到你想要的结果:
Hello there. Let us help you. Hey mr! We got you! Welcome to our humbo home. See you soon!
为什么之前的正则无效?
你之前写的\d+\.?\d*%;是用来匹配数字(可能带小数点)加百分号的模式,和你要匹配的地名、邮箱完全不沾边,自然找不到任何匹配项,也就不会有替换效果啦。
如果你的[^,]+换成更灵活的规则,但根据你给出的示例,当前的正则已经完全够用了。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

