[英]Java Pattern issue
I am getting a text from the DB which contains Strings of the form 我从DB获取包含表单字符串的文本
CO<sub>2</sub>
In order to recognize this I wrote the following code 为了识别这个,我写了下面的代码
String footText = "... some text containing CO<sub>2</sub>";
String co2HTML = "CO<sub>2</sub>";
Pattern pat = Pattern.compile(co2HTML);
Matcher mat = pat.matcher(footText);
final boolean hasCO2 = mat.matches();
The problem is that hasCO2 is always false although the inout text has that substring. 问题是hasCO2总是假的,尽管inout文本有子串。 What is wrong hete? 有什么不对的?
Thanks! 谢谢!
You should use find()
instead of matches()
, since the latter tries to match the entire string against the pattern rather than perform a search. 您应该使用find()
而不是matches()
,因为后者会尝试将整个字符串与模式匹配,而不是执行搜索。
From the Javadoc : 来自Javadoc :
- The
matches
method attempts to match the entire input sequence against the pattern.matches
方法尝试将整个输入序列与模式匹配。- The
lookingAt
method attempts to match the input sequence, starting at the beginning, against the pattern.lookingAt
方法尝试将输入序列(从头开始)与模式匹配。- The
find
method scans the input sequence looking for the next subsequence that matches the pattern.find
方法扫描输入序列,寻找与模式匹配的下一个子序列。
Also, the pattern in question doesn't really require regular expressions; 此外,有问题的模式并不需要正则表达式; you could use String.indexOf()
to perform the search. 您可以使用String.indexOf()
来执行搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.