gnagy
gnagy

Reputation: 1

Why dont work this java program?

I want get This imageurl.txt file, from this source.txt , with the program. If i try only with "p" or "p2", then works. But both the two pattern, writes out ,nothing.

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

public class imageurl
{
    public static void main(String[] args) 
            throws IOException
    {
    for ( int i = 1; i < 5000; i++ )
        {
        toContent(i);
        Pattern p = Pattern.compile("cacheimages/(.*)[\"][ ]*target=");
        Pattern p2 = Pattern.compile("</b>[ ]*[(](.*)[)]</div>");
        BufferedReader r = new BufferedReader(new FileReader("source\\source"+i+".txt"));
        String line;
        FileWriter writer = new FileWriter("imageurl\\imageurl"+i+".txt");
        while ((line = r.readLine()) != null )
            {
            Matcher m = p.matcher(line);
            Matcher m2 = p2.matcher(line);
            while (m.find())
            while (m2.find())
                {
                String c = (m.group(1));
                String c2 = (m2.group(1));
                System.out.println("<name>"+c2+"</name>_<url>http://www.geocaching.hu/cacheimages/"+c+"</url>"+"\n");
                writer.write("<name>"+c2+"</name>_<url>http://www.geocaching.hu/cacheimages/"+c+"</url>"+"\n");
                }
            }
            writer.close();
        }
    }
    private static void toContent(int i)
    {
    }
}

Upvotes: 0

Views: 149

Answers (2)

phatfingers
phatfingers

Reputation: 10250

The problem is that the two expressions you're matching don't exist on the same line at the same time. You need to read two lines at once to get the results you want.

. . .
String line2;
while ((line = r.readLine()) != null )
    Matcher m=p.matcher(line);
    if (m.find()) {
        if (line2 = r.readLine() != null) {
            Matcher m2=p2.matcher(line);
            if (m2.find()) {
                String c=m.group(1);
                String c2=m2.group(1);
                String outmsg=String.format("<name>%s</name>_<url>http://www.geocaching.hu/cacheimages/%s</url>\n", c2, c);
                System.out.print(outmsg);
                writer.write(outmsg);
            }
        }
        writer.close();
    }
}

Upvotes: 1

Calin Andrei
Calin Andrei

Reputation: 176

If you have for every m.find() one m2.find() then it is ok if you have only one while and an if instead of the second while.

Else if you have more m2.find() for one m.find() then you have to check if the positions of m2.find() is between the two m.find() (the correct one and the next one).

Upvotes: 0

Related Questions