Nabh Limits Undefined
Nabh Limits Undefined

Reputation: 23

Regex match for string literal including escape sequence

This works just fine for normal string literal ("hello").

"([^"]*)"

But I also want my regex to match literal such as "hell\"o". This what i have been able to come up with but it doesn't work.

("(?=(\\")*)[^"]*")

here I have tried to look ahead for <\">.

Upvotes: 0

Views: 1264

Answers (3)

Pshemo
Pshemo

Reputation: 124275

How about

Pattern.compile("\"((\\\\\"|[^\"])*)\"")// 
                         ^^ - to match " literal
                     ^^^^   - to match \ literal
                     ^^^^^^ - will match \" literal

or

Pattern.compile("\"((?:\\\\\"|[^\"])*)\"")// 

if you don't want to add more capturing groups.

This regex accept \" or any non " between quotation marks.


Demo:

    String input = "ab \"cd\" ef \"gh \\\"ij\"";
    Matcher m = Pattern.compile("\"((?:\\\\\"|[^\"])*)\"").matcher(input);
    while (m.find())
        System.out.println(m.group(1));

Output:

cd
gh \"ij

Upvotes: 1

Sabuj Hassan
Sabuj Hassan

Reputation: 39443

Try with this one:

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

\\\" to match \" or,

[^\"] to match anything by "

Upvotes: 0

Jerry
Jerry

Reputation: 71598

Use this method:

"((?:[^"\\\\]*|\\\\.)*)"

[^"\\\\]* now will not match \ anymore either. But on the other alternation, you get to match any escaped character.

Upvotes: 0

Related Questions