简体   繁体   English

Java正则表达式字符串替换

[英]Java regex string replace

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. 我想编写正则表达式,将其用<a> html标记替换“ am”,并获得第二个字符串作为替换第一个字符串的结果。

Problem is nesting in quotes and text inside tag. 问题是嵌套在引号和标记内的文本。

For example if I try to replace string "am" in this example: 例如,如果在此示例中尝试替换字符串“ am”:

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! 提前致谢!

如果是这样的简单情况,则可以使用简单的环顾四周方法来确保所匹配的事物没有被><包围,但是它周围有单词边界( \\b ):

(?<!>)\bam\b(?!<)

下面的正则表达式匹配的只有am的空白包围。

str.replaceAll("(?<=\\s)am(?=\\s)","<a href=\"am.html\">am</a>")

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? 但是对于这种简单的情况,像替换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> ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM