2014-03-07 26 views
1

我不得不提到,我仍然不明白正则表达式是如何工作的。请看下面的代码。这个正则表达式替换了什么?

titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.(?=\\s|$)", " "); 

这里,titleAndBodyContainerString。但是,它取代了什么空间?句号?逗号?问号?

+0

正则表达式教练解释的正则表达式一个很好的机制。 –

回答

4

它用一个空格替换一个点,后面跟着空格或输入的结尾。

| dot (double-escaped) 
| | look ahead non-capturing group 
| | | whitespace (double-escaped) 
| | | | or 
| | | || end of input ("$") 
\\.(?=\\s|$) 

检查API here

+0

我的好运,这意味着它不会取代“,?,/,(,), - 等? –

+0

@GloryOfSuccess不好。 – Mena

0

在您的代码中,它将用空格替换所有点(.)()。但是有条件。点必须在空白处或行末。

例如:

alex is dead. and alive.dead 
alex is dead. 

在上述两个例子中,将只更换dead后的点,因为它有空间或行结束。

0

它替代点后跟一个空格字符\t\n\x0B\f\rend of lineend of input与空间

1

enter image description here

图片从: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_"

0
titleAndBodyContainer = titleAndBodyContainer.replaceAll("\\.(?=\\s|$)", " "); 

此相匹配后面有一个空格或字符串的结束点(.),并用空格替换它。

如果你想更换?/()为好,你可以尝试像:

titleAndBodyContainer = titleAndBodyContainer.replaceAll("[\\.\\?\\/\\(\\)](?=\\s|$)", " ");