2013-12-09 56 views
3

我已經搜索了幾個小時的答案,現在仍然沒有什麼能夠解決特定的編程困境。這不適用於學校或工作。我正在開發一個應用程序,需要根據正則表達式執行預定義的數據清理任務。我遇到的一個具體表達是刪除單詞和數字之間的空格字符。下面是示例要求:用於條件刪除空白空間的Java模式RegEx

word 123   ==> word123 
123 word   ==> 123word 
world 123 wide  ==> word123wide 
world wide 123  ==> world wide123 
world wide 123 456 ==> world wide123 456 

正則表達式環視似乎是正確的做法,但仍然無法弄清楚如何應用表達式有超過2個字塊的短語。

在此先感謝。

回答

4

使用lookarounds兩個Pattern S之間的組合和alternance,因爲這樣的:

//    | preceded by digit 
//    |  | one whitespace 
//    |  | | followed by non-digit 
//    |  | |  | OR 
//    |  | |  | | preceded by non-digit 
//    |  | |  | |  | one whitespace 
//    |  | |  | |  | | followed by digit 
String pattern = "(?<=\\d)\\s(?=\\D)|(?<=\\D)\\s(?=\\d)"; 
// test Strings 
String test0 = "word 123"; 
String test1 = "123 word"; 
String test2 = "world 123 wide"; 
String test3 = "world wide 123"; 
String test4 = "world wide 123 456"; 
// testing output: replace all found matches 
// (e.g. one per String in this case) 
// with empty 
System.out.println(test0.replaceAll(pattern, "")); 
System.out.println(test1.replaceAll(pattern, "")); 
System.out.println(test2.replaceAll(pattern, "")); 
System.out.println(test3.replaceAll(pattern, "")); 
System.out.println(test4.replaceAll(pattern, "")); 

輸出:

word123 
123word 
world123wide 
world wide123 
world wide123 456 
+0

+1,但我可能會使用'\\ S +'而不是僅僅' \\ s':「空白」通常表示任意數量的空白字符 – Bohemian

+0

@Mena - 一個真正的正則表達式嚮導 – RyPope

+0

@波希米亞的好點。我在我的評論中添加了「一個空格」,但它可以很容易地被任何數字替換:) – Mena