Another Regular Expressions question

J

jeffM

I'm searching for the following substrings TAG001,TAG002 and TAG003 from
this string

"VCE1246KYTAG001ZX178TAG002DHU7749TAG003"

Pattern pattern = Pattern.compile( "'(TAG00\\d[^T]*){3}'" );
Matcher matcher =
pattern.matcher("VCE1246KYTAG001ZX178TAG002DHU7749TAG003");

System.out.println( matcher.groupCount() );

and the System.out is printing only 1.Where am I going wrong here?

jeff
 
H

Hop Pocket

From the java API, matcher.groupCount():

Returns the number of capturing groups in this matcher's pattern. I.e.
(TAG00\\d[^T]*). The parentheses denote a capturing group.



That's just saying that you have one capturing group in your pattern for the
matcher.
 
C

Christophe Vanfleteren

jeffM said:
I'm searching for the following substrings TAG001,TAG002 and TAG003 from
this string

"VCE1246KYTAG001ZX178TAG002DHU7749TAG003"

Pattern pattern = Pattern.compile( "'(TAG00\\d[^T]*){3}'" );
Matcher matcher =
pattern.matcher("VCE1246KYTAG001ZX178TAG002DHU7749TAG003");

System.out.println( matcher.groupCount() );

and the System.out is printing only 1.Where am I going wrong here?

jeff

What you need is matcher.find().
 
A

Alan Moore

I'm searching for the following substrings TAG001,TAG002 and TAG003 from
this string

"VCE1246KYTAG001ZX178TAG002DHU7749TAG003"

Pattern pattern = Pattern.compile( "'(TAG00\\d[^T]*){3}'" );
Matcher matcher =
pattern.matcher("VCE1246KYTAG001ZX178TAG002DHU7749TAG003");

System.out.println( matcher.groupCount() );

and the System.out is printing only 1.Where am I going wrong here?

jeff

String str = "VCE1246KYTAG001ZX178TAG002DHU7749TAG003";

Pattern p = Pattern.compile("TAG00\\d");
Matcher m = p.matcher(str);

while (m.find())
{
System.out.println(m.group());
}

That's how you would find all the matches in the target string. In
order to apply the pattern to the target, you have to call one of the
Matcher methods: matches(), lookingAt(), or find(). Once you've done
that, with a return value of 'true', the group() method returns
whatever the pattern actually matched. If you have capturing groups
in your pattern, you can retrieve what they matched by calling
group(1), group(2), etc. (group(0) is the same as group()). For
instance, if you just wanted to know what the final digit was in the
example above, you could do this:

String str = "VCE1246KYTAG001ZX178TAG002DHU7749TAG003";

Pattern p = Pattern.compile("TAG00(\\d)");
Matcher m = p.matcher(str);

while (m.find())
{
System.out.println("Found tag number " + m.group(1));
}
 

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,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top