2015-08-13 31 views
4

在下面的句子去除相鄰的3個逗號:刪除單個逗號,但不要在一個句子

String res = [what, ask, about, group, differences, , , or, differences, in, conditions, |? |] 

我想刪除一個逗號(,),但不希望刪除三個相鄰的逗號。

我試過這個正則表達式:res.replaceAll("(,\\s)^[(,\\s){3}]", " ")但它不工作。

+0

你能發佈你期待的結果嗎? – Pshemo

回答

3

一個簡單的方法來做到這一點是通過鏈接兩個replaceAll調用,而不是隻用一個模式:

String input = 
"[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]"; 

System.out.println(
    input 
     // replaces 
     //   | comma+space not preceded/followed by other comma 
     //   |     | with space 
     .replaceAll("(?<!,), (?!,)", " ") 
     // replaces 
     //   | 3 consecutive comma+spaces 
     //   |   | with single comma+space 
     .replaceAll("(,){3}", ", ") 
); 

輸出

[what ask about group differences, or differences in conditions |? |] 
+0

謝謝......它正在工作:) – Jayant

+0

@Jayant不客氣! – Mena

2

您可以在find使用此代碼特色更換方法:

String s = "[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]"; 
StringBuffer result = new StringBuffer(); 
Matcher m = Pattern.compile("((?:\\s*,){3})|,").matcher(s); 
while (m.find()) { 
    if (m.group(1) != null) { 
     m.appendReplacement(result, ","); 
    } 
    else { 
     m.appendReplacement(result, ""); 
    } 
} 
m.appendTail(result); 
System.out.println(result.toString()); 

參見IDEONE demo

輸出:[what ask about group differences, or differences in conditions |? |]

正則表達式 - ((?:\\s*,){3})|, - 匹配2個選擇:要麼帶有可選空格分開3個逗號(即捕獲),或者只是一個逗號。如果我們得到一個捕獲,我們用逗號替換。如果捕獲爲空,我們匹配一個逗號,將其刪除。

1

您還可以使用:

String res = "[what, ask, about, group, differences, , , or, differences, in, conditions, |? |]"; 
res.replaceAll("(?<=\\w),(?!\\s,)|(?<!\\w),\\s",""); 
  • (?<=\\w),(?!\\s,) - 由字preceeded逗號,而不是由其他 逗號休耕,
  • (?<!\\w),\\s - 逗號不是字
1

另一個preceeded可能的方法:

.replaceAll("(,\\s){2,}|,", "$1") 
  • (,\\s){2,}將嘗試找到兩個或兩個以上,和將存儲其中的一個索引爲1
  • ,可以匹配這是沒有被前面的正則表達式消耗逗號組,這意味着它是一個逗號

更換$1使用比賽從第1組

  • 如果我們發現, , ,我們想用,代替它,這樣的文本將被放置在組1中
  • 如果我們只找到,那麼我們想用它替換它,並且因爲之前的正則表達式找不到它匹配的所有組(它們在我們的情況是組1)也是空的。