首页 文章

用于匹配双引号但不是反斜杠双引号的正则表达式

提问于
浏览
0

我需要正则表达式来匹配双引号字符 " but not if it is preceded by a backslash ,即 \" .

我得到了 [^\\]" 但是它选择了两个字符: " 和其他(除了\)在前面,我只需要选择 " 字符 .

我需要解析流中看起来像这样的行: command "string1" "string2" string可以包含空格和转义双引号 . 我需要拆分它,以便我得到命令,string1和string2作为数组 .

提前致谢

2 回答

  • 3

    你可以使用负面的后卫: (?<!\\)" .

    (?<!reg1)reg2 表示 reg2 必须以 reg1 开头 . 请注意,不会捕获 reg1 .

    现在在Java代码中,你的正则表达式看起来会略有不同,因为你需要转义双引号和两个反斜杠:

    String regex = "(?<!\\\\)\"";
    
  • 1

    您可以使用negative lookbehind:匹配 " 前面没有 \\ ,例如:

    Pattern pat = Pattern.compile("(?<!\\\\)\"");
    
    System.out.println(pat.matcher("quote \" not escaped").find());
    // prints true, the " doesn't follow a \
    
    System.out.println(pat.matcher("quote \\\" escaped").find());
    // prints false, the " follows a \
    

相关问题