【发布时间】:2014-06-07 05:11:40
【问题描述】:
以下场景需要 Java 正则表达式模式:
案例 1:
输入字符串:
"a"
匹配:
a
案例 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$^
案例 4:
输入字符串:
"a b c
匹配:
None - since the quotes are unbalanced, hence pattern match fails.
案例 5:
输入字符串:
"a b" "c
匹配:
None - since the quotes are unbalanced, hence pattern match fails.
案例 6:
输入字符串:
"a b" p q r "x y z"
匹配:
a b
p
q
r
x y z
案例 7:
输入字符串:
"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 添加了 Java 代码和一些输入字符串。
-
我猜你的实际字符串不仅仅是单个小写字母。它们是否需要包含大写字母、数字、特殊字符等?他们应该多长时间有限制吗?
-
@CAustin 可能有大写字母、数字、特殊字符等,但没有限制。
-
我不确定你想要什么,但我敢肯定答案是在你到达这个之前。
标签: java regex arguments pattern-matching command-line-arguments