Link to home
Start Free TrialLog in
Avatar of Tolgar
Tolgar

asked on

How to return the matched string in Java?

Hi,
I have the following code:

             
      if ((buff.matches("<a.*?href=['\"](http://.*?)['\"].*?>.*mytests"))) {
                	    FileLine = $1;
                   }

Open in new window


As you may guess this does not work correctly.

I want to return the matched string from this code and assign it to FileLine.

How can I do it?


Thanks,

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Try
FileLine = buff.group(1);

Open in new window

('buff' would have to be of type Matcher)
if myString  is your string where you are looking for the pattern, this is how you print all matches:

  Pattern p = Pattern.compile("<a.*?href=['\"](http://.*?)['\"].*?>.*mytests");
            Matcher m = p.matcher(myStrting);
        while(m.find()){
            String s1 = s.substring(m.start(),m.end());
   System.out.println(s1);
}
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tolgar
Tolgar

ASKER

@ CEHJ:

What should I make to this code to make it compile?

    		   java.lang.String buff = null;
               while (in.hasNextLine()) {
            	   buff = in.nextLine();
                   if ((buff.matches("<a.*?href=['\"](http://.*?)['\"].*?>.*mytests"))) {
                	    FileLine = buff.group(1);
                   }
               }

Open in new window



Thanks,
What type is 'buff' - String or Matcher?
Doh - it's String ;) If you're looking linewise, you'll find the last code i posted is simpler
:)