我不确定你是否可以在一次Matcher.match
调用中做到这一点,但你可以通过循环来做到这一点。
这段代码通过Matcher.find()
重复使用解决了上面提到的所有情况:
Pattern pattern = Pattern.compile("\"([^\"]+)\"|'([^']+)'|\\S+");
List<String> testStrings = Arrays.asList("foo bar", "\"foo bar\"","'foo bar'", "'foo bar", "\"'foo bar\"", "foo bar'", "foo bar\"", "\"foo bar\" \"stack overflow\"", "\"foo' bar\" \"stack overflow\" how do you do");
for (String testString : testStrings) {
int count = 1;
Matcher matcher = pattern.matcher(testString);
System.out.format("* %s%n", testString);
while (matcher.find()) {
System.out.format("\t* group%d: %s%n", count++, matcher.group(1) == null ? matcher.group(2) == null ? matcher.group() : matcher.group(2) : matcher.group(1));
}
}
这打印:
* foo bar
* group1: foo
* group2: bar
* "foo bar"
* group1: foo bar
* 'foo bar'
* group1: foo bar
* 'foo bar
* group1: 'foo
* group2: bar
* "'foo bar"
* group1: 'foo bar
* foo bar'
* group1: foo
* group2: bar'
* foo bar"
* group1: foo
* group2: bar"
* "foo bar" "stack overflow"
* group1: foo bar
* group2: stack overflow
* "foo' bar" "stack overflow" how do you do
* group1: foo' bar
* group2: stack overflow
* group3: how
* group4: do
* group5: you
* group6: do