arvindwill
arvindwill

Reputation: 1992

Java Regular Expression first matching char

String text = "ref=\"ar\" alias=\"as sa\" value=\"asa\"";

Actually i want get the value of all the data between the double quotes of ref and alias . Have framed the regular expression too. But the prob i am facing is for alias it is not matching the first double quotes but the last one. I want data only upto the first double quotes

String patternstr="(alias=\".*\")|(ref=\"[[\\w]]*\")";    
String patternstr2Level="\".*\"";

In first matching the two parameter will be acquired and in the second matching data in quotes will be acquired

Current Result:

"ar"

"as sa" value="asa"

Required Result:

"ar"

"as sa"

Upvotes: 2

Views: 2461

Answers (3)

Justin Peel
Justin Peel

Reputation: 47072

You just need to make your match a little bit lazier. I believe that

String patternstr="(alias=\".*?\")|(ref=\".*?\")";

should do the trick. By using .*? instead of just .*, that part of the match becomes lazy. In other words, it will try to match the first double quote that it finds rather than matching as much stuff as possible until it gets to the last double quotes. I tested it in Python and it worked great.

Upvotes: 5

Adam Dymitruk
Adam Dymitruk

Reputation: 129526

match the last one as well but modify the group to be excluded from the result with the ?> modifier.

See this for more info:

http://www.regular-expressions.info/atomic.html

Upvotes: 0

Thomas
Thomas

Reputation: 88707

Try String patternstr="(alias=\"[\\w\\s]*\")|(ref=\"[[\\w]]*\")";

Upvotes: 0

Related Questions