我有以下需要被過濾Java的正則表達式來過濾電話號碼
0173556677 (Alice), 017545454 (Bob)
這是電話號碼是如何加入到一個文本視圖例子字符串。我希望文字看起來像這樣
0173556677;017545454
是否有方法使用正則表達式更改文本。這樣的表達會是怎樣的?或者你推薦其他方法?
我有以下需要被過濾Java的正則表達式來過濾電話號碼
0173556677 (Alice), 017545454 (Bob)
這是電話號碼是如何加入到一個文本視圖例子字符串。我希望文字看起來像這樣
0173556677;017545454
是否有方法使用正則表達式更改文本。這樣的表達會是怎樣的?或者你推薦其他方法?
你可以做如下:
String orig = "0173556677 (Alice), 017545454 (Bob)";
String regex = " \\(.+?\\)";
String res = orig.replaceAll(regex, "").replaceAll(",", ";");
// ^remove all content in parenthesis
// ^replace comma with semicolon
在'regex'變量中,有一個'?'。我已經嘗試執行沒有'?'的代碼,變量'res'獲取'0173556677'而不是'0173556677; 017545454'。正則表達式意義上的'?'是指可選字符。這到底意味着什麼? – stackoverflowery 2014-04-03 10:05:50
此解決方案與不包含數字的任意字符串分隔電話號碼:
String orig = "0173556677 (Alice), 017545454 (Bob)";
String[] numbers = orig.split("\\D+"); //split at everything that is not a digit
StringBuilder sb = new StringBuilder();
if (numbers.length > 0) {
sb.append(numbers[0]);
for (int i = 1; i < numbers.length; i++) { //concatenate all that is left
sb.append(";");
sb.append(numbers[i]);
}
}
String res = sb.toString();
,或者與com.google.common .base.Joiner:
String[] numbers = orig.split("\\D+"); //split at everything that is not a digit
String res = Joiner.on(";").join(numbers);
PS。與最佳投票示例中的要求略有偏差,但似乎我不能只添加一個字符(應該是replaceAll(", ", ";")
,昏迷後有空格,或者\\s
),我不想篡改某人的代碼。
看看Google的libphonenumber – fge 2012-01-03 08:41:01