简体   繁体   中英

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 #!#

Lorem #!#ASD## => matches #!#

Lorem #!## => no match

Lorem##!# => no match

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 '#'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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