なぜ他のすべての人がそのような複雑な正規表現や長いコードを提案しているのか理解できません。基本的に、文字列から 2 種類のものを取得する必要があります: スペースでも引用符でもない一連の文字、および 2 種類の引用符に対して、間に引用符を入れずに引用符で開始および終了する一連の文字です。これらは、次の正規表現で簡単に一致させることができます。
[^\s"']+|"([^"]*)"|'([^']*)'
リストに引用符が必要ないため、キャプチャ グループを追加しました。
この Java コードはリストを作成し、一致した場合はキャプチャ グループを追加して引用符を除外し、キャプチャ グループが一致しなかった場合 (引用符で囲まれていない単語が一致した場合) は全体的な正規表現一致を追加します。
List<String> matchList = new ArrayList<String>();
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<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}