我不明白为什么所有其他人都提出这么复杂的正则表达式或这么长的代码。本质上,你想从你的字符串中获取两种东西:不是空格或引号的字符序列,以及以引号开头和结尾的字符序列,两种引号之间没有引号。您可以很容易地将这些内容与这个正则表达式相匹配:[^\s"']+|"([^"]*)"|'([^']*)'
我添加了捕获组,因为您不希望列表中的引号。
此Java代码构建列表,如果匹配以排除引号,则添加捕获组;如果捕获组不匹配,则添加总体regex匹配(未引用的单词匹配)。List matchList = new ArrayList();Pattern regex = Pattern.compile("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
Matcher regexMatcher = regex.matcher(subjectString);while (regexMatcher.find()) {
if (regexMatcher.group(1) != null) {
// Add double-quoted string without the quotes
matchList.add(regexMatcher.group(1));
} else if (regexMatcher.group(2) != null) {
// Add single-quoted string without the quotes
matchList.add(regexMatcher.group(2));
} else {
// Add unquoted word
matchList.add(regexMatcher.group());
}}
如果您不介意在返回的列表中使用引号,则可以使用更简单的代码:List matchList = new ArrayList();Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(subjectString);while (regexMatcher.find()) {
matchList.add(regexMatcher.group());}