1

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.

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Man I feel like an idiot. I now understand what i did wrong... Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.