javaregex

Need a java.util.regex to retrieve value in quotes


I have this string:

String str = "message version=1 filename=\"double \"\"quote\"\" file.txt\" size=32591";

I want to get the filename value with a regex. What I've used so far is:

Matcher fileNameMatcher = Pattern.compile("\\s*filename=\"(.*?)\"\\s*").matcher(str);
while (fileNameMatcher.find()) {
    int n = fileNameMatcher.groupCount();
    for (int i = 0; i < n; i++)
        this.fileName = fileNameMatcher.group(i + 1);
}

If there are quotes in the filename, it will always be doubled (""), so I want a regex that will ignore double doublequotes and retrieve the quoted filename value from the message


Solution

  • You may use

    Pattern.compile("filename=\"([^\"]*(?:\"{2}[^\"]*)*)\"")
    

    See the regex demo.

    Pattern details