Rick
Rick

Reputation: 91

Java Regex giving only first or last match and not all of them

I'm trying to get all matches with the following code:

 String line = ("<option value=\"001\">Values go here </option> <option value=\"002\">More values in here</option>");
Pattern p = Pattern.compile("<option value=\"(.*)\">(.*)</option> ");
Matcher finder = p.matcher(line);
while(finder.find())
{
     System.out.println( finder.group(1));
     System.out.println( finder.group(2));
}

Yet I only get the last or first match. (Depending if a space is on the end or at the start of the pattern)

What am I doing wrong?

Upvotes: 1

Views: 893

Answers (1)

anubhava
anubhava

Reputation: 784958

Make your regex non-greedy (lazy):

Pattern p = Pattern.compile("<option value=\"(.*?)\">(.*?)</option>");

OR better to:

Pattern p = Pattern.compile("<option value=\"([^\"]*)\">([^<]*)</option>");

Problem in your regex is use of .* which is greedy and matching more text than you desired.

PS: Also note that I have remove extra space after </option>

Upvotes: 6

Related Questions