java String.replaceAll正则表达式问题 [英] java String.replaceAll regex question

查看:152
本文介绍了java String.replaceAll正则表达式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下文字的字符串

 字符串my_string =你好世界。它是冷酷的brrrrrr!br br ; 

我想更换每个隔离的 br with < br />



问题是我想避免转换字符串to

 你好世界。它很冷< br /> rrrrr!< br />< br / >中; 

我想做的是将字符串(使用replaceAll)转换为

 你好世界。这是冷酷的brrrrrr!< br />< br />; 

我确定这很简单,但我的正则表达式不正确。

  my_string.replaceAll(\\sbr\\ | | \\sbr $,< br /> ;); 

我的正则表达式假设找到'空白''b''r ''whitespace'或''whitespace''b''r''行尾''/ b>

但它错过了我的字符串中的最后一个br

 你好世界。这是冷酷的brrrrrr!< br /> br

我做错了什么? TKS!

解决方案

使用

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






你的正则表达式不起作用,因为在

 ␣br␣br
^

模式 \sbr\s 将消耗整个␣br␣,离开

 < br /> br 
^

现在此 br 没有前面的空格来匹配 \\ \\ sbr $ ,所以它会被遗漏。



另一方面, \ b ,意思是字边界,是零宽度断言,即它不会消耗任何字符。因此,这些空格将被保留,所有孤立的 br 将被匹配。


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!

解决方案

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.

这篇关于java String.replaceAll正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆