Need a Java regex pattern for the following scenario:
Case 1:
Input string:
"a"
Matches:
a
Case 2:
Input string:
"a b"
Matches:
a b
Case 3:
Input string:
"aA Bb" cCc 123 4 5 6 7xy "\"z9" "\"z9$^"
Matches:
aA Bb
cCc
123
4
5
6
7xy
"z9
"z9$^
Case 4:
Input string:
"a b c
Matches:
None - since the quotes are unbalanced, hence pattern match fails.
Case 5:
Input string:
"a b" "c
Matches:
None - since the quotes are unbalanced, hence pattern match fails.
Case 6:
Input string:
"a b" p q r "x y z"
Matches:
a b
p
q
r
x y z
Case 7:
Input string:
"a b" p q r "x y \"z\""
Matches:
a b
p
q
r
x y "z"
Case 8:
Input string:
"a b" p q r "x \"y \"z\""
Matches:
a b
p
q
r
x "y "z"
And of course, the simplest one:
Case 9:
Input string:
a b
Matches:
a
b
Tried using a pattern, but it doesn't seem to match all above cases.
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[]) and place that Java code here.