java - 如何解析可以包含转义双引号的双引号分隔字符串

标签 java regex string parsing

我需要从看起来像这样的流中解析行: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/

相关文章:

c - scanf() 和 printf() 中的字符串变量名之前的 & 符号或没有 & 符号?

java - `javax.filter.Filter` 没有正确添加 CORS header

java - 打开附件面板的操作

java - 为什么 protected 变量在类级别可见?

python - 使用 RegEx 从伪标签之间提取数据(不能使用 BeautifulSoup)

c - 为什么 strcmp 对完整填充的字符数组给出不同的响应?

java - 解码 HTML 转义字符

java - 使用正则表达式进行拆分(使用正则表达式的经验有限)

java - 旧正则表达式代码的必要解释

c - 存储在注册表中的字符串值如何不以 null 结尾?