gpt4 book ai didi

Java模式问题

转载 作者:行者123 更新时间:2023-11-29 03:53:08 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com