File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Best way of matching substring Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Best way of matching substring" Watch "Best way of matching substring" New topic

Best way of matching substring

William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

How should I find "red" in "This is a sentence with the word red in it."? My first inclination is to do a step by step character matching loop. But that seems a bit non-java-ish. I don't see any help in the String api. So do I have to use something like Matcher class?

Please ignore post, I have no idea what I am talking about.
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

You could do this with a regular expression, as I think you've worked out. Alternatively (and more easily) you could use this method of the String class:

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
William Barnes
Ranch Hand

Joined: Mar 16, 2001
Posts: 986

Ya, that is the one I missed.
Carol Enderlin
Ranch Hand

Joined: Oct 10, 2000
Posts: 1364
Not that there is anything wrong with indexOf(), but 1.4 added a regex method to String:

public boolean matches(String regex)
I agree. Here's the link:
subject: Best way of matching substring
It's not a secret anymore!