java String.replaceAll regex question

牧云@^-^@ 提交于 2019-12-02 13:28:56

Use

my_string.replaceAll("\\bbr\\b", "<br />");

Your regex doesn't work because in

␣br␣br
^

The pattern \sbr\s will consume the whole ␣br␣, leaving with

<br />br
      ^

now there is no preceding space for this br to match \sbr$, so it will be missed.

On the other hand, the \b, meaning a word-boundary, is a zero-width assertion, i.e. it won't consume any characters. Therefore the spaces will be kept and all isolated br's will be matched.

"hello world. it's cold out brrrrrr!<br />br" Your final 'br' isn't preceded by whitespace. What's supposed to happen?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!