2016-06-01 88 views
-1

我有一個像Java「||」字符串替換用 「OR」

「年齡= 18 ||名稱= '的Mistic' || civilstatus = '結婚' ||性別= '0'」

字符串

我需要替換「||」按「OR」。我試了下面的代碼。

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0'".replaceAll("||", "OR")); 

,但我得到

「ORaORgOReOR OR = OR OR1OR8OR OR |和| OR ORnORaORmOReOR OR = OR OR'ORMORiORsORtORiORcOR'OR OR |和| OR ORcORiORvORiORlORsORtORaORtORuORsOR OR = OR OR」 ORmORaORrORrORiOReORdOR'OR OR |和| OR ORgOReORnORdOReORrOR OR = OR OR'OR0OR'OR」

我需要的是

「年齡= 18或名稱= '的Mistic' OR civilstatus = '結婚',性別= '0'」

我怎樣才能做到這一點。

編輯 我已閱讀this question的問題和答案,這不是類似的。因爲這個問題是關於替換字符串,我的問題是關於讓我的代碼不熟悉的結果。

+0

@ErwinBolwidt這個問題是不是我的問題重複。 –

+0

爲什麼它不是重複的?這個問題的OP與你有同樣的困惑,答案是一樣的。你也應該看看你自己問題的最高投票答案。重複的答案更好地解釋了爲什麼你可能會在'replaceAll'和'replace'之間混淆。 –

+0

這是因爲'replaceAll'需要一個正則表達式,比如'split'。看看鏈接的問題。 – Tunaki

回答

5

|在正則表達式中有一個特殊含義。你需要逃避它。

public static void main(String[] args) { 
    String s = "age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0' "; 
    System.out.println(s.replaceAll("\\|\\|", "OR")); 
} 

O/P:

age = 18 OR name = 'Mistic' OR civilstatus = 'married' OR gender = '0' 

PS:另外,您也可以使用Pattern.quote()逃避特殊字符。

String st = Pattern.quote("||"); 
System.out.println(s.replaceAll(st, "OR")); 
2

您必須轉義「||」,因爲它們是正則表達式中的元字符。

用途:

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0'".replaceAll("\\|\\|", "OR")); 

你之所以越來越:

「ORaORgOReOR OR = OR OR1OR8OR OR |和| OR ORnORaORmOReOR OR = OR OR'ORMORiORsORtORiORcOR'OR OR |或| OR ORcORiORvORiORlORsORtORaORtORuORsOR OR = OR OR'ORmORaORrORrORiOReORdOR'OR OR |和| OR ORgOReORnORdOReORrOR OR = OR OR'OR0OR'OR」

是因爲正則表達式「||」用「OR」表示「將空字符串或空字符串或空字符串替換」。換句話說,用「OR」替換所有空字符串。

1

您需要轉義輸入字符串中的特殊字符。

1

您可以使用以下代碼替換所有'||'與「或」

String str = "age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0' "; 
System.out.println(str.replaceAll("\\|\\|", "OR")); 
10

爲什麼在不想用正則表達式替換時使用replaceAll

儘量只使用普通的replace

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' 
    || gender = '0'".replace("||", "OR")); 

輸出

年齡= 18或名稱= '的Mistic' OR civilstatus = '結婚',性別= '0'

2

使用Pattern.quote

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0'".replaceAll(Pattern.quote("||"), "OR")); 
2

您可以使用替代來代替的replaceAll,請嘗試使用以下..

System.out.println("age = 18 || name = 'Mistic' || civilstatus = 'married' || gender = '0' ".replace("||", "OR")); 
+0

你爲什麼要分配一個字符串,然後甚至不使用它? –

+0

哦,是的,謝謝你不需要拿字符串,我糾正.. –