简体   繁体   English

从字符串中删除的正则表达式匹配

[英]RegEx match to remove from string

I need to remove #!# instances from string when there's not # before or after the instance.当实例之前或之后没有#时,我需要从字符串中删除#!#实例。

For example...例如...

LoremImpsum#!#Dolor => matches #!# LoremImpsum#!#Dolor => 匹配#!#

Lorem #!#ASD## => matches #!# Lorem #!#ASD## => 匹配#!#

Lorem #!## => no match Lorem #!## => 不匹配

Lorem##!# => no match Lorem##!# => 不匹配

my code so far:到目前为止我的代码:

foreach (Match match in Regex.Matches(formattedHtml, @"(?<!#)(#!#)(?!#)")
    formattedHtml = formattedHtml.Replace(match.Value, "");

But it seems to me that negative lookahead or lookbehind wont work.但在我看来,负面的前瞻或后视是行不通的。 Thanks.谢谢。

It looks like you code fails in places where there are multiple occurrences and only one of them was supposed to be replaced.看起来您的代码在多次出现的地方失败,并且应该只替换其中一个。

Your Regex does it was supposed to do.你的正则表达式做了它应该做的。 However, the problem was with the Replace code.但是,问题出在替换代码上。 Instead of following而不是跟随

foreach (Match match in Regex.Matches(formattedHtml, @"(?<!#)(#!#)(?!#)")
 formattedHtml = formattedHtml.Replace(match.Value, "");

You should use你应该使用

formattedHtml = Regex.Replace(formattedHtml,@"(?<!#)(#!#)(?!#)","");

According to your initial code, if it finds a match, it would replace all the occurances in the string even if it has a preceeding/succeeding '#'根据您的初始代码,如果找到匹配项,它会替换字符串中的所有出现,即使它有前面/后面的 '#'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM