2

The sample source code to match is

String string="welcome";
String k="a\"welcome";

I am using "(\"[^(\")]*\")" regex in java.

But this extracts

0:"welcome"
0:"a\"

Expected output is

0:"welcome"
0:"a\"welcome"

What change should i make in regex to get the expected output ?

Java source :

private static String pattern1="(\"[^(\")]*\")";
public void getStrings(){
    Pattern r = Pattern.compile(pattern1);
    Matcher m = r.matcher("String string=\"welcome\";\n" +
            "String k=\"a\\\"welcome\";");


    while(m.find()){
        System.out.println("0:"+m.group(0));
    }
}
1
  • You should tell us what pattern is not matched, or better what's the principle of matching or not. Commented Sep 6, 2014 at 14:07

2 Answers 2

1

Just use lookahead and lookbehind in your regex,,

(?<==)(".*?")(?=;)

Get the value from group index 1.

DEMO

Pattern r = Pattern.compile("(?<==)(\".*?\")(?=;)");
Matcher m = r.matcher("String string=\"welcome\";\n" +
            "String k=\"a\\\"welcome\";");
while(m.find()){
        System.out.println("0:"+m.group(1));
}

Output:

0:"welcome"
0:"a\"welcome"

OR

Use the greediness of *,

Pattern r = Pattern.compile("(\".*\")");

OR

It skips the double quotes which are preceded by a backslash,

Pattern r = Pattern.compile("(\\\".*?(?<=[^\\\\])\\\")");
Sign up to request clarification or add additional context in comments.

2 Comments

you could try this also regex101.com/r/vN2vU4/4 . It just skips the double quotes which are proceeded by a backslash.
or this, (\".*?[^\\]\")
0

Why do you even bother with variable assignment. You know that everything within "" is a string.

"(.+)"\s*; should do it just fine.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.