m3div0
m3div0

Reputation: 1596

C# Regex replace in string only outside tags

I have a string, which represents part of xml.

string text ="word foo<tag foo='a' />another word "

and I need to replace particular words in this string. So I used this code:

Regex regex = new Regex("\\b" + co + "\\b", RegexOptions.IgnoreCase);
return regex.Replace(text, new MatchEvaluator(subZvyrazniStr));
static string     subZvyrazniStr(Match m)
    {
        return "<FtxFraze>" + m.ToString() + "</FtxFraze>";
    }

But the problem of my code is, that it also replaces string inside tags, which i don't want to. So what should I add, to replace words only outside tags?

Ex.: when I set variable co to "foo" I want to return "word <FtxFraze>foo</FtxFraze><tag foo='a' />another word"

Thanks

Upvotes: 2

Views: 1725

Answers (3)

Anirudha
Anirudha

Reputation: 32797

This is what you want

(?<!\<[\w\s]*?)\bfoo\b(?![\w\s]*?>)

works here

I had answered a related question here

Upvotes: 1

Qtax
Qtax

Reputation: 33908

A simple trick like this may suffice in some cases if you are not that picky:

\bfoo\b(?![^<>]*>)

Upvotes: 5

DelegateX
DelegateX

Reputation: 719

Try this regex:

Regex r = new Regex(@"\b" + rep + @".*?(?=\<)\b", RegexOptions.IgnoreCase);

Upvotes: 0

Related Questions