简体   繁体   中英

C# regual expression needed

I have a bunch of text and in that text I would like to replace every "EXAMPLE" word that does NOT contain a az or AZ character in front of it.. so something like " [^az]EXAMPLE ".. But when deleting I just want to delete the "EXAMPLE", not the misc character in front of it or any characters behind it...

So in "BLABLAEXAMPLBLA EXAMPLEBLA" i want to output "BLABLAEXAMPLBLA BLA"

I hope this is preety clear:)

Thank you for your time!

You can achieve this using negative lookbehind :

string cleanString = Regex.Replace(originalString, "(?<![a-zA-Z])EXAMPLE", "");

You can also use match evaluator. I think more elastic but more complicated too...

var regex = new Regex("[^a-z](?<a>EXAMPLE)");
var text = "BLABLAEXAMPLBLA EXAMPLEBLA";
MatchEvaluator evaluator = RemoveExample;
text = regex.Replace(text, evaluator);

...

private static string RemoveExample(Match m)
{
    return m.Value.Replace(m.Groups["a"].Value, "");
}

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