我从数据库中获取文本,其中包含以下形式的字符串
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/