简体   繁体   中英

Java Pattern issue

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!

You should use find() instead of matches() , since the latter tries to match the entire string against the pattern rather than perform a search.

From the 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.

Also, the pattern in question doesn't really require regular expressions; you could use String.indexOf() to perform the search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM