Search code examples
javastringdesign-patternsmatcher

java pattern for a url


I want to read from a file each line and edit only the lines that presents a url from a specific server... My code is like...

   Scanner ReadIsbn = new Scanner (new FileReader ("C:/Users/...."));        

    Pattern pat = Pattern.compile("http:////www.librarything.com//isbn//");

    while ( ReadIsbn.hasNextLine()){

        String line = ReadIsbn.nextLine();
        Matcher m = pat.matcher(line);
        if (m.matches() == true) {
            EDIT line....

        }

    }

}

And it is not working... In fact m.matches() is always false.. In the file i give as input, there are lines like:

1)   http://www.librarything.com/isbn/0-9616696-7-5.html
2)   http://www.librarything.com/isbn/0-86078-322-7.html
Cultural tourism : how the arts can help market tourism products, how 
blablabla

(i want to edit only the first two lines of the example)


Solution

  • You need not escape forward slashes in your pattern. This should do

    Pattern pat = Pattern.compile("http://www.librarything.com/isbn/");
    

    Another problem is that matches method tries to match pattern against entire input text. Use

     if (m.find()){
            EDIT line....
     }
    

    If you just want to check the prefix as you are doing here, then you can also use String#startsWith method