1

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!

2
  • 1
    What's wrong with String.contains(CharSequence)? Commented Oct 17, 2011 at 14:05
  • Well, in fact the code is more complex. I've posted the kern of the problem and not the whole code. I do need Patterns. Anyway, thanks for your comment. Commented Oct 17, 2011 at 14:28

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.