1

How can i get Strings between double quotes using Regex in Java?

_settext(_textbox(0,_near(_span("My Name"))) ,"Brittas John");

ex: I need My Name and Brittas John

2 Answers 2

3

Get the matched group from index 1 that is captured by enclosing inside the parenthesis (...)

"([^"]*)"

DEMO

Pattern explanation:

  "                        '"'
  (                        group and capture to \1:
    [^"]*                    any character except: '"' (0 or more times) (Greedy)
  )                        end of \1
  "                        '"'

sample code:

Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher("_settext(_textbox(0,_near(_span(\"My Name\"))) ,\"Brittas John\");");
while (m.find()) {
    System.out.println(m.group(1));
}
Sign up to request clarification or add additional context in comments.

Comments

2

Try this regex..

public static void main(String[] args) {
    String s = "_settext(_textbox(0,_near(_span(\"My Name\"))) ,\"Brittas John\");";
    Pattern p = Pattern.compile("\"(.*?)\"");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group(1));
    }
}

O/P :

My Name
Brittas John

9 Comments

but it's slow in performance as suggested by me. Look at regex101 - regex debugger for no of steps. I am not sure that is it giving true result.
@user3218114 how is the performance any slower? In both cases the parser should stop as soon as it sees a ".
Look at the no of steps needed to extract the desired result. What is the difference between greedy and lazy pattern? which is faster?
@user3218114 lazy is actually generally faster. It knows exactly when to stop. In this specific case, your greedy should perform equally though. But I still fail to see why it would be any faster.
@Cruncher look at the demo that I shared you and click on regex debugger link then inspect the steps needed to extract the desired result. Expend all steps.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.