Java模式问题

标签 java regex pattern-matching

我从数据库中获取文本,其中包含以下形式的字符串

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 文本具有该子字符串。 hete 有什么问题?

谢谢!

最佳答案

您应该使用 find() 而不是 matches(),因为后者尝试将整个字符串与模式匹配而不是执行搜索。

来自Javadoc :

  • The matches method attempts to match the entire input sequence against the pattern.
  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

此外,所讨论的模式实际上并不需要正则表达式;你可以使用 String.indexOf()执行搜索。

关于Java模式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7794780/

相关文章:

java - Hibernate JPA 序列(非 Id)

Java/SQLite - 如何编译 -DTHREADSAFE=1?

java - 将 IN 子句列表添加到 JPA 查询

正则表达式匹配括号部分内的 ulimit

ruby - 正则表达式 "punct"字符类根据 Ruby 版本匹配不同的字符

scala - Scala 案例模式是一等的吗?

scala - 在akka中带有@符号的案例

algorithm - 查找重复位模式的有效算法?

java - 复制线程的 session

javascript - 如何通过用户代理字符串检测 IE7,忽略以怪异模式运行的较新 IE 版本