带有可能转义字符的String的正则表达式

时间:2012-02-29 23:08:19

标签: java regex

我曾经在这里问过这个问题Regular expression that does not contain quote but can contain escaped quote并得到了回复,但不知怎的,我无法在Java中使用它。

基本上我需要编写一个正则表达式,该表达式匹配以引号开头和结尾的有效字符串,如果它们被转义,则可以在两者之间加上引号。

在下面的代码中,我基本上想要匹配所有三个字符串并打印true,但不能。

正确的正则表达式应该是什么?

由于

public static void main(String[] args) {

    String[] arr = new String[] 
            { 
                "\"tuco\"", 
                "\"tuco  \" ABC\"",
                "\"tuco \" ABC \" DEF\"" 
            };

    Pattern pattern = Pattern.compile("\"(?:[^\"\\\\]+|\\\\.)*\"");

    for (String str : arr) {
        Matcher matcher = pattern.matcher(str);
        System.out.println(matcher.matches());
    }

}

1 个答案:

答案 0 :(得分:0)

问题不是你的正则表达式,而是你的测试字符串。解析文字字符串时,将消耗第二个和第三个示例字符串上的内部引号之前的单个反斜杠。传递给正则表达式引擎的字符串在引用之前没有反斜杠。 (尝试将其打印出来。)以下是您的功能的测试版本,它按预期工作:

import java.util.regex.*;
public class TEST
{
    public static void main(String[] args) {

        String[] arr = new String[] 
                { 
                    "\"tuco\"", 
                    "\"tuco  \\\" ABC\"",
                    "\"tuco \\\" ABC \\\" DEF\"" 
                };

//old:  Pattern pattern = Pattern.compile("\"(?:[^\"\\\\]+|\\\\.)*\"");
        Pattern pattern = Pattern.compile(
            "# Match double quoted substring allowing escaped chars.     \n" +
            "\"              # Match opening quote.                      \n" +
            "(               # $1: Quoted substring contents.            \n" +
            "  [^\"\\\\]*    # {normal} Zero or more non-quote, non-\\.  \n" +
            "  (?:           # Begin {(special normal*)*} construct.     \n" +
            "    \\\\.       # {special} Escaped anything.               \n" +
            "    [^\"\\\\]*  # more {normal} non-quote, non-\\.          \n" +
            "  )*            # End {(special normal*)*} construct.       \n" +
            ")               # End $1: Quoted substring contents.        \n" +
            "\"              # Match closing quote.                        ", 
            Pattern.DOTALL | Pattern.COMMENTS);

        for (String str : arr) {
            Matcher matcher = pattern.matcher(str);
            System.out.println(matcher.matches());
        }
    }
}

我已将您的正则表达式替换为改进版本(取自MRE3)。请注意,这个问题会被问到很多。请参阅this answer,其中我比较了几个功能相同的表达式。