Searching a pattern

G

gonas

How can i search for a pattern in a string.

ie. if the pattern is "xyz" then the string can be tokenized only when
the pattern "xyz" appears and not for each "x","y","z"

also the same for multiple patterns like "xyz" and "abc". finding the
string between the two patterns.

usage of indexOf is very much killing tell me some other ways
 
A

Alan Moore

How can i search for a pattern in a string.

ie. if the pattern is "xyz" then the string can be tokenized only when
the pattern "xyz" appears and not for each "x","y","z"

also the same for multiple patterns like "xyz" and "abc". finding the
string between the two patterns.

usage of indexOf is very much killing tell me some other ways

If you're using jdk1.4+, you can use the built-in regular expression
package (for earlier versions, there are third party packages you can
use). So, to find all occurrences of "xyz" or abc" you would do this:

Pattern p = Pattern.compile("xyz|abc");
Matcher m = p.matcher(inputString);
while (m.find())
{
System.out.println("found: " + m.group());
}

Here's a site that has a pretty good regex tutorial:

http://www.regular-expressions.info/

Also be sure and read the javadocs for the Pattern and Matcher classes
(in the java.util.regex package).
 
O

Oscar kind

gonas said:
How can i search for a pattern in a string.

ie. if the pattern is "xyz" then the string can be tokenized only when
the pattern "xyz" appears and not for each "x","y","z"

also the same for multiple patterns like "xyz" and "abc". finding the
string between the two patterns.

usage of indexOf is very much killing tell me some other ways

What is it exactly that you are trying to do?

If you're searching for the pattern itself, have a look at the package
java.util.regex (especially the classes Pattern and Matcher therein).

If you're using the pattern as a delimiter and want to tokenize the string
in which it occurs, have a look at java.lang.String#split(String) and
java.lang.String#split(String,int).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top