java String.replaceAll 正则表达式问题
我有一个包含以下文本的字符串,
String my_string = "hello world. it's cold out brrrrrr! br br";
我想用
替换每个isolated br
问题是我想避免将字符串转换为
"hello world. it's cold out <br />rrrrr! <br /> <br />";
我想做的是将字符串(使用replaceAll)转换为
"hello world. it's cold out brrrrrr! <br /> <br />";
我确信这非常简单,但我的正则表达式不正确。
my_string.replaceAll("\\sbr\\s|\\sbr$", "<br />");
我的正则表达式应该找到 'whitespace' 'b' 'r' 'whitespace' OR 'whitespace' 'b' 'r' 'end of line'
但它错过了我的最后一个“br”字符串
"hello world. it's cold out brrrrrr!<br />br"
我做错了什么? TKS!
I have a string that contains the following text
String my_string = "hello world. it's cold out brrrrrr! br br";
I'd like to replace each isolated br with <br />
The issue is that I'd like to avoid converting the string to
"hello world. it's cold out <br />rrrrr! <br /> <br />";
What I'd like to do is convert the string (using replaceAll) to
"hello world. it's cold out brrrrrr! <br /> <br />";
I'm sure this is very simple, but my regex isn't correct.
my_string.replaceAll("\\sbr\\s|\\sbr$", "<br />");
my regex is supposed to find 'whitespace' 'b' 'r' 'whitespace' OR 'whitespace' 'b' 'r' 'end of line'
but it misses the final "br" in my string
"hello world. it's cold out brrrrrr!<br />br"
what am I doing wrong?? TKS!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
您的正则表达式不起作用,因为在
模式
\sbr\s
中将消耗整个␣br␣
,现在该
没有前面的空格br
来匹配\sbr$
,所以它会被错过。另一方面,
\b
表示字边界,是一个零宽度断言,即它不会消耗任何字符。因此,空格将被保留,并且所有独立的br
将被匹配。Use
Your regex doesn't work because in
The pattern
\sbr\s
will consume the whole␣br␣
, leaving withnow 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 isolatedbr
's will be matched."hello world. it's Cold out brrrrrrr!
最后的 'br' 前面没有空格。应该发生什么?br"
"hello world. it's cold out brrrrrr!<br />br"
Your final 'br' isn't preceded by whitespace. What's supposed to happen?