我有一句話:"we:PR show:V"
。 我只想匹配":"
之後和"\\s"
之前使用正則表達式模式匹配器的那些字符。 我使用了以下模式:使用正則表達式忽略java中的模式
Pattern pattern=Pattern.compile("^(?!.*[\\w\\d\\:]).*$");
但它沒有奏效。 獲得輸出的最佳模式是什麼?
我有一句話:"we:PR show:V"
。 我只想匹配":"
之後和"\\s"
之前使用正則表達式模式匹配器的那些字符。 我使用了以下模式:使用正則表達式忽略java中的模式
Pattern pattern=Pattern.compile("^(?!.*[\\w\\d\\:]).*$");
但它沒有奏效。 獲得輸出的最佳模式是什麼?
以下正則表達式假定以下冒號(依次由非冒號之後)的任何非空白字符是有效匹配:
[^:]+:(\S+)(?:\s+|$)
使用像:
String input = "we:PR show:V";
Pattern pattern = Pattern.compile("[^:]+:(\\S+)(?:\\s+|$)");
Matcher matcher = pattern.matcher(input);
int start = 0;
while (matcher.find(start)) {
String match = matcher.group(1); // = "PR" then "V"
// Do stuff with match
start = matcher.end();
}
的模式匹配,依次爲:
的循環繼續,只要正則表達式的字符串中的項目匹配,指數start
,其目前的比賽結束後總是被調整爲指向的開始。
String match = matcher.group(1); // =「PR」,那麼「V」只返回「R」和「V」而不是「PR」和「V」 –
對不起,有點草率。移動括號內的+,這應該修復它。請參閱編輯。 – Mac
對於這樣的情況,因爲這,如果你使用的是Java,它可能更容易做一些與子:
String input = "we:PR show:V";
String colon = ":";
String space = " ";
List<String> results = new ArrayList<String>();
int spaceLocation = -1;
int colonLocation = input.indexOf(colon);
while (colonLocation != -1) {
spaceLocation = input.indexOf(space);
spaceLocation = (spaceLocation == -1 ? input.size() : spaceLocation);
results.add(input.substring(colonLocation+1,spaceLocation);
if(spaceLocation != input.size()) {
input = input.substring(spaceLocation+1, input.size());
} else {
input = new String(); //reached the end of the string
}
}
return results;
這將是比試圖匹配正則表達式更快。
要說得很清楚,你的意思是你想在上面的測試用例中匹配字符串'PR'? – Mac
@Mac是的,但不僅PR我也需要V。 –