我不得不提到,我仍然不明白正则表达式是如何工作的。请看下面的代码。这个正则表达式替换了什么?
titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.(?=\\s|$)", " ");
这里,titleAndBodyContainer
是String
。但是,它取代了什么空间?句号?逗号?问号?
我不得不提到,我仍然不明白正则表达式是如何工作的。请看下面的代码。这个正则表达式替换了什么?
titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.(?=\\s|$)", " ");
这里,titleAndBodyContainer
是String
。但是,它取代了什么空间?句号?逗号?问号?
在您的代码中,它将用空格替换所有点(.
)()。但是有条件。点必须在空白处或行末。
例如:
alex is dead. and alive.dead
alex is dead.
在上述两个例子中,将只更换dead
后的点,因为它有空间或行结束。
它替代点后跟一个空格字符\t\n\x0B\f\r
或end of line
或end of input
与空间
图片从:Regexper.comhttp://www.regexper.com/#\.%28%3F%3D\s|%24%29
实施例:
System.out.println("Hello. ".replaceAll("\\.(?=\\s|$)", "_"));
System.out.println("Hello.".replaceAll("\\.(?=\\s|$)", "_"));
System.out.println(".".replaceAll("\\.(?=\\s|$)", "_"));
System.out.println(". ".replaceAll("\\.(?=\\s|$)", "_"));
System.out.println(".com".replaceAll("\\.(?=\\s|$)", "_"));
System.out.println(". Hi".replaceAll("\\.(?=\\s|$)", "_"));
输出i s:
Hello_ //there is a space after Hello_
Hello_//no space this time
_
_ //again, space after _
.com
_ Hi
重要的是空白区域或行尾字符不被消耗。他们只用于检查比赛,但不能替换。这就是为什么在第一个例子,"Hello. "
导致"Hello_ "
并不仅仅是"Hello_"
titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.(?=\\s|$)", " ");
此相匹配后面有一个空格或字符串的结束点(.
),并用空格替换它。
如果你想更换?/()
为好,你可以尝试像:
titleAndBodyContainer = titleAndBodyContainer.replaceAll("[\\.\\?\\/\\(\\)](?=\\s|$)", " ");
正则表达式教练解释的正则表达式一个很好的机制。 –