Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to write regex for replacing string.

There are string examples:

I am student.

I <a href="am.html">am</a> student.

I want to write regex which will replace "am" with <a> html tag, and get second string as result of replacing the first string.

Problem is nesting in quotes and text inside tag.

For example if I try to replace string "am" in this example:

I <a href="am.html">am</a> am student.

Result should be:

I <a href="am.html">am</a> <a href="am.html">am</a> student.

Thanks in advance!

share|improve this question
    
possible duplicate of replacing regex in java string –  benzado Jul 4 '12 at 18:12

3 Answers 3

up vote 1 down vote accepted

If it's a simple case like this you could use simple lookarounds to make sure that the thing you are matching is not surrounded by > and < but that it has word boundaries (\b) around it:

(?<!>)\bam\b(?!<)
share|improve this answer
    
It looks like very nice solution. But does it covers replacing word followed by comma, question mark or exclamation? Thank you very much. –  user1500221 Jul 4 '12 at 0:38
    
@user1500221, yes it does, all ams would match in am,am.am/am?!am-%am. –  Qtax Jul 4 '12 at 0:47
    
I cannot make this work...I am using this, but i am doing somethin wrong. Link in code is some string. tekst.replaceAll("(?<!>)\\bam\\b(?!<)", link); –  user1500221 Jul 4 '12 at 1:17
    
@user1500221, here is an example: ideone.com/YU1tY. –  Qtax Jul 4 '12 at 1:34
    
Thanks, you helped a lot! –  user1500221 Jul 4 '12 at 1:38

Below regex only matches am surrounded by whitespace.

str.replaceAll("(?<=\\s)am(?=\\s)","<a href=\"am.html\">am</a>")
share|improve this answer

I can see some answers related to regex string posted already so there's no need for me to post another one. But as for this simple case, how about something as simple as replacing String? Or perhaps the real problem is more complicated than this? My solution for this case is:

s.replaceAll(" am ", " <a href=\"am.html\">am</a> ");
share|improve this answer
    
Replacing is supposed to cover replacing word followed by comma, question mark, dot or exclamation? That makes me problems. –  user1500221 Jul 4 '12 at 0:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.