string.matches("。*")返回false [英] string.matches(".*") returns false

查看:101
本文介绍了string.matches("。*")返回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

任何想法可能出错?当我将内容打印到stdout时,它看起来没问题。

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

以下是从PDF中提取文本的代码(我使用的是iText 5.0.1):

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);


推荐答案

默认情况下,与换行符不匹配。所以我的猜测是你的内容包含一个换行符。

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!

一些例子:

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

(?s)在最后一个示例中,将导致匹配换行符。所以(?s)。* 将匹配任何字符串。

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

这篇关于string.matches("。*")返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆