[英]string.matches(“.*”) returns false
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. 当我将
content
打印到stdout时,它看起来没问题。
Here is the code for extracting text from the PDF (I am using iText 5.0.1): 以下是从PDF中提取文本的代码(我使用的是iText 5.0.1):
PdfReader reader = new PdfReader(source);
PdfTextExtractor extractor = new PdfTextExtractor(reader,
new SimpleTextExtractingPdfContentRenderListener());
return extractor.getTextFromPage(1);
By default, the .
默认情况下
.
does not match line breaks. 与换行符不匹配。 So my guess is that your
content
contains a line break. 所以我的猜测是你的
content
包含一个换行符。
Also note that matches
will match the entire string, not just a part of it: it does not do what contains
does! 另请注意,
matches
将匹配整个字符串,而不仅仅是其中的一部分:它不会执行contains
!
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 .
最后一个例子中的
(?s)
将导致.
to match line breaks as well. 也可以匹配换行符。 So
(?s).*
will match any string. 所以
(?s).*
将匹配任何字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.