string.matches(".*") returns false
Asked Answered
N

1

22

In my program, I have a string (obtained from an external library) which doesn't match any regular expression.

String content = // extract text from PDF
assertTrue(content.matches(".*")); // fails
assertTrue(content.contains("S P E C I A L")); // passes
assertTrue(content.matches("S P E C I A L")); // fails

Any idea what might be wrong? When I print content to stdout, it looks ok.

Here is the code for extracting text from the PDF (I am using iText 5.0.1):

PdfReader reader = new PdfReader(source);
PdfTextExtractor extractor = new PdfTextExtractor(reader,
    new SimpleTextExtractingPdfContentRenderListener());
return extractor.getTextFromPage(1);
Nonobservance answered 7/3, 2010 at 15:48 Comment(1)
marked as favourite as it's not the first time I've been hit by such java bomb.Uriniferous
R
36

By default, the . does not match line breaks. So my guess is that your content contains a line break.

Also note that matches will match the entire string, not just a part of it: it does not do what contains does!

Some examples:

String s = "foo\nbar";
System.out.println(s.matches(".*"));       // false
System.out.println(s.matches("foo"));      // false
System.out.println(s.matches("foo\nbar")); // true
System.out.println(s.matches("(?s).*"));   // true

The (?s) in the last example will cause the . to match line breaks as well. So (?s).* will match any string.

Reflux answered 7/3, 2010 at 15:52 Comment(2)
You saved my day :) I didn't realize that matches() wants to match the entire string.Norther
@Miroslav, yes, the mistake is easily made since many languages "look" for a match instead of matching the entire string. Good to hear you resolved it!Reflux

© 2022 - 2024 — McMap. All rights reserved.