2014-03-07 27 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|$)", " ");