需要一个Java正则表达式模式来处理以下情况:
案例1: 输入字符串:
Case 2:
输入字符串:
"案例3:"
"输入字符串:"
Case 6:
输入字符串:
当然,最简单的一个案例:
第9个案例:
输入字符串:
尝试使用了一个模式,但似乎不能匹配所有上述情况。
案例1: 输入字符串:
"a"
匹配:
a
Case 2:
输入字符串:
"a b"
匹配:
a b
"案例3:"
"输入字符串:"
"aA Bb" cCc 123 4 5 6 7xy "\"z9" "\"z9$^"
匹配结果:
aA Bb
cCc
123
4
5
6
7xy
"z9
"z9$^
Case 4:
Input string:
"a b c
匹配:
None - since the quotes are unbalanced, hence pattern match fails.
Case 5:
Input string:
"a b" "c
匹配项:
None - since the quotes are unbalanced, hence pattern match fails.
Case 6:
输入字符串:
"a b" p q r "x y z"
匹配:
a b
p
q
r
x y z
第七种情况:
输入字符串:
"a b" p q r "x y \"z\""
匹配:
a b
p
q
r
x y "z"
案例8:
输入字符串:
"a b" p q r "x \"y \"z\""
匹配:
a b
p
q
r
x "y "z"
当然,最简单的一个案例:
第9个案例:
输入字符串:
a b
匹配:
a
b
尝试使用了一个模式,但似乎不能匹配所有上述情况。
public List<String> parseArgs(String argStr) {
List<String> params = new ArrayList<String>();
String pattern = "\\s*(\"[^\"]+\"|[^\\s\"]+)";
Pattern quotedParamPattern = Pattern.compile(pattern);
Matcher matcher = quotedParamPattern.matcher(argStr);
while (matcher.find()) {
String param = matcher.group();
System.out.println(param);
params.add(param);
}
return params;
}
public void test(String argStr) {
String[] testStrings = new String[]{"a", "a b", "a b \"c\"", "a b \"c"};
for(String s: testStrings){
parseArgs(s);
}
}
String[]
)中,并将Java代码放在这里。 - anubhava