Regex again - non-greedy matching

K

kaeli

Okay, so I want this to return only the first match, like <a
href='someUrl.html'>some link</a>, but it returns the whole match. How
to I match the *shortest* occurance?

TIA

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class testPatternMatching extends Object
{
public static void main(String [] args)
{
String pageContent = "<a href='someUrl.html'>some link</a> more
text blah <a href='anotherUrl.html'>another link</a> more text blah";
String s = null;
try
{
Pattern p = Pattern.compile("<a.*href=.*>.*?</a>",
Pattern.DOTALL);
Matcher m = p.matcher(pageContent);
s = m.find()?m.group():"";

System.out.println(s);
}
catch (Exception e)
{
System.out.println("Exception occured:");
System.out.println(e.getMessage());
}
}
};

--
 
M

Martin Honnen

kaeli said:
Okay, so I want this to return only the first match, like <a
href='someUrl.html'>some link</a>, but it returns the whole match. How
to I match the *shortest* occurance?

TIA

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class testPatternMatching extends Object
{
public static void main(String [] args)
{
String pageContent = "<a href='someUrl.html'>some link</a> more
text blah <a href='anotherUrl.html'>another link</a> more text blah";
String s = null;
try
{
Pattern p = Pattern.compile("<a.*href=.*>.*?</a>",
Pattern.DOTALL);

Apply non-greedy matching to all your quantifiers:

Pattern p = Pattern.compile("<a.*?href=.*?>.*?</a>",
Pattern.DOTALL);
 
K

kaeli

Apply non-greedy matching to all your quantifiers:

Pattern p = Pattern.compile("<a.*?href=.*?>.*?</a>",
Pattern.DOTALL);

Oh, dear.
*shuffles feet, looks at floor*

Thanks!

--
 
H

hiwa

kaeli said:
Okay, so I want this to return only the first match, like <a
href='someUrl.html'>some link</a>, but it returns the whole match. How
to I match the *shortest* occurance?

TIA

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class testPatternMatching extends Object
{
public static void main(String [] args)
{
String pageContent = "<a href='someUrl.html'>some link</a> more
text blah <a href='anotherUrl.html'>another link</a> more text blah";
String s = null;
try
{
Pattern p = Pattern.compile("<a.*href=.*>.*?</a>", [^<]?

Pattern.DOTALL);
Matcher m = p.matcher(pageContent);
s = m.find()?m.group():"";

System.out.println(s);
}
catch (Exception e)
{
System.out.println("Exception occured:");
System.out.println(e.getMessage());
}
}
};

--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top