1

have the following problem using regex and $ in a string. Wondring if anyone can assist.

bla in text below is random words.

string text = "<id='$text1$text2$text3'><div>bla bla bla text3 bla bla</div>";
string pattern = "\btext3\b";
text = Regex.Replace(text, pattern, "####");

If i do above, it will replace both text3. I only want to change the value in the div element so the result becomes: <id='$text1$text2$text3'> <div>bla bla bla #### bla bla</div>.

Thanks in advance!

6
  • From my favourite website: "\b Matches at the position between a word character (anything matched by \w) and a non-word character (anything matched by [^\w] or \W) as well as at the start and/or end of the string if the first and/or last characters in the string are word characters." - regular-expressions.info/reference.html Commented Jan 25, 2011 at 16:10
  • Ive read the "specs", regarding \b, dont fully understands it. Thats why im asking. Can I solve my problem some otherway? Ive tried some combinations but they become very "complex". Commented Jan 25, 2011 at 16:20
  • @Loppus fyi, you should add @ name to reply to someone, they get a message in their inbox that way. Using regular expressions to parse HTML or XML never works as well as one would hope. In your particular case, do you want to match "text3" in all cases except where it is preceded with a "$"? Or is there an other equally specific case that doesn't involve parsing HTML/XML with regular expressions? If so... narrow it down to that. Commented Jan 25, 2011 at 17:00
  • What if the string was <id='$text1$text2$text3'> <div>bla bla bla priceis2$text3$ bla bla</div> ? Commented Jan 25, 2011 at 17:36
  • @Kobi, that's why I'm asking if that's possible in his particular case. If it is possible, regular expressions do not work very well (at all) for parsing HTML/XML and a more complicated solution would be in order. Commented Jan 25, 2011 at 17:42

2 Answers 2

1
string pattern = @"\btext3\b(?![^<>]*>)";

This quick-and-dirty solution relies on several simplifying assumptions, as all regexes must if they're to be used on HTML. For example, it assumes there will never be any angle brackets in attribute values. That's legal (in HTML at least), but it's extremely rare in practice.

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

Comments

1
string pattern = ">text3<";
text = Regex.Rplace(text,pattern,">####<");

1 Comment

Its never that easy, please check my edited main post, thanks anyways

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.