Java模式问题
我从数据库中获取包含以下形式的字符串的文本
CO<sub>2</sub>
为了识别这一点,我编写了以下代码
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();
问题是 hasCO2 始终为 false,尽管 inout 文本具有该子字符串。 有什么问题吗?
谢谢!
I am getting a text from the DB which contains Strings of the form
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.
What is wrong hete?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用
find()
而不是matches()
,因为后者尝试将整个字符串与模式进行匹配,而不是执行搜索。来自 Javadoc:
此外,所讨论的模式实际上并不需要正则表达式;而是需要正则表达式。您可以使用
String.indexOf()
执行搜索。You should use
find()
instead ofmatches()
, since the latter tries to match the entire string against the pattern rather than perform a search.From the Javadoc:
Also, the pattern in question doesn't really require regular expressions; you could use
String.indexOf()
to perform the search.