使用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
+1,但我可能會使用'\\ S +'而不是僅僅' \\ s':「空白」通常表示任意數量的空白字符 – Bohemian
@Mena - 一個真正的正則表達式嚮導 – RyPope
@波希米亞的好點。我在我的評論中添加了「一個空格」,但它可以很容易地被任何數字替換:) – Mena