Regular Expressions

J

jeffM

If I wanted to search a string such as the one shown below, for these
substrings TAG001 ,TAG002,TAG003 using regular expressions , how would I do
it?
String strToSearch="VCE1246KYTAG001ZX178TAG002DHU7749TAG003

jeff
 
K

Kevin Henry

Daqian Yang said:
Cover this string to a char array, and use a for loop to search tagxxxx
That is clearly not answering his question. He wanted to use Regular
Expressions.
If you use the Pattern and Matcher classes in java.util.regex it can be done
like this:

Pattern p = Pattern.compile("(TAG0001)|(TAG0002)|(TAG0003)");
// or "TAG\d{4}" if you simply want any four digit
number afterwards
Matcher m = p.matcher(strToSearch);
if (m.matches()) {
// it matched
} else {
// it didn't
}

For more information see:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/package-summary.html

Kevin
 
R

Robert Olofsson

: Pattern p = Pattern.compile("(TAG0001)|(TAG0002)|(TAG0003)");
: // or "TAG\d{4}" if you simply want any four digit
: number afterwards
: Matcher m = p.matcher(strToSearch);
: if (m.matches()) {

Do you not mean
while (m.find ()) {
// do something
}

instead? matches tries to match the full string...

/robo
 

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,785
Messages
2,569,624
Members
45,319
Latest member
LorenFlann

Latest Threads

Top