2014-03-05 23 views
2

我想在Java字符串添加轉義字符"'"(單引號),但只有當有奇數次發生的使用正則表達式如何使用兩個單引號

對於防爆取代奇數單引號:

  1. 如果字符串是像"string's property"然後輸出應爲"string''s property"
  2. 如果字符串是像"string''s property"然後輸出應爲"string''s property"
+0

3個報價會發生什麼? –

回答

1

嘗試這種情況:

\'(\')? 

演示(替換瓦特第i個'

http://regexr.com?38eeh

+0

Ehm。那麼關於JavaScript的問題呢? – Mena

+0

@KeyurArdeshana很高興知道它爲你工作。爲了社區的利益,將答案標記爲正確(旁邊的「勾號」),這是讓其他人知道的好方法。 ;-) –

0

試試這個代碼(偶數)。

public static void main(String[] args) { 
    String str = "a''''''b"; 
    str = str.replaceAll("[^']'('')*[^']", "###"); 
    System.out.println(str); 
} 

然後試試這個(奇數)。

public static void main(String[] args) { 
    String str = "a'''''''b"; 
    str = str.replaceAll("[^']'('')*[^']", "###"); 
    System.out.println(str); 
} 
+0

這將不起作用,因爲你的模式將匹配'''''' –

+0

嗯。確實。但爲什麼?!哦,OK nvm。 –

+0

感謝但沒有正常工作,因爲我嘗試使用像'keyur'這樣的字符串'''''怎麼回事?'而且結果是'keyur'是什麼?我在哪裏預期成爲'keyur'''''''是什麼?看看keyur –

0

嘗試這種情況:

// input that will be replaced 
String replace = "string's property"; 
// input that won't be replaced 
String noReplace = "string''s property"; 
// String representation of the Pattern for both inputs 
//     |no single quote before... 
//     | |single quote 
//     | | |... no single quote after 
String pattern = "(?<!')'(?!')"; 
// Will replace found text with main group twice --> found 
System.out.println(replace.replaceAll(pattern, "$0$0")); 
// Will replace found text with main group twice --> not found, no replacement 
System.out.println(noReplace.replaceAll(pattern, "$0$0")); 

輸出:

string''s property 
string''s property 
相關問題