我需要从看起来像这样的流中解析行:command "string1" "string2"
字符串可以包含空格和转义双引号。我需要拆分它,以便将 command、string1 和 string2 作为数组元素。我认为 split() 与正则表达式匹配 "
但不是 \"
( .split("(?<!\\\\)\"")
) 可以胜任,但我听说这不是一个好主意。
在 Java 中有更好的方法吗?
最佳答案
类似的东西应该可以解决问题,假设你想在适用时删除外部双引号(如果你不这样做,只需更改第一个捕获组以也包括引号):
public class Demo {
private static final Pattern WORD =
Pattern.compile("\"((?:[^\\\\\"]|\\\\.)*)\"|([^\\s\"]+)");
public static void main(String[] args) {
String cmd =
"command " +
"\"string with blanks\" " +
"\"anotherStringBetweenQuotes\" " +
"\"a string with \\\"escaped\\\" quotes\" " +
"stringWithoutBlanks";
Matcher matcher = WORD.matcher(cmd);
while (matcher.find()) {
String capturedGroup = matcher.group(1) != null ? matcher.group(1) : matcher.group(2);
System.out.println("Matched: " + capturedGroup);
}
}
}
输出:
Matched: command
Matched: string with blanks
Matched: anotherStringBetweenQuotes
Matched: a string with \"escaped\" quotes
Matched: stringWithoutBlanks
正则表达式有点复杂,所以值得解释一下:
[^\\\\\"]
匹配反斜杠或双引号以外的所有内容\\\\.
匹配反斜杠后跟任何字符(包括双引号),即转义字符(?:[^\\\\\"]|\\\\.)*
匹配任何转义或非转义字符序列,但不捕获组(因为(?:)
)"\"((?:[^\\\\\"]|\\\\.)*)\"
匹配包含在双引号中的任何此类序列并捕获其内部引语([^\\s\"]+)
匹配任何非空白字符的非空序列,并将其捕获到一个组中
关于java - 如何解析可以包含转义双引号的双引号分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38809708/