0

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!

4

3 回答 3

1

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(?!<)
于 2012-07-04T00:27:19.373 回答
0

Below regex only matches am surrounded by whitespace.

str.replaceAll("(?<=\\s)am(?=\\s)","<a href=\"am.html\">am</a>")
于 2012-07-04T00:32:57.057 回答
-1

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> ");
于 2012-07-04T00:42:31.123 回答