Substring matching with regular expressions

Hi all,

I'm having one heck of a time with regular expressions and I'm hoping that someone can lend me a hand. What I'm trying to do is look for a particular substring within a string using a pattern. Here's my code:

import java.util.regex.*;

publicclass RegExTest{

publicstaticvoid main(String[] args){

String testStr ="This 9 XX is my test string.";

Pattern pattern = Pattern.compile("\\b\\d+\\sXX\\b");

Matcher matcher = pattern.matcher(testStr);

System.out.println("Matches: " + matcher.matches());

}

}

So what I'm trying to do is find substrings that start with a number, followed by whitespace, followed by XX, all within a word boundary. Unfortunately this is not working for me and I don't know why. Can anyone help?

[1186 byte] By [j.svazica] at [2007-10-3 4:14:06]
# 1
You must use find() instead of matches() since the latter will try to match ALL the string and not just a substring like the former does:System.out.println("Matches: " + matcher.find());Regards
jfbrierea at 2007-7-14 22:15:19 > top of Java-index,Core,Core APIs...
# 2

Firstly, the Java Programming forum is the appropriate place to ask regex questions.

Secondly, have you seen the documentation at http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html ? It clearly states that the matches() method "Attempts to match the entire region against the pattern." What you want to do is attempt to find the next subsequence of the input sequence that matches the pattern.

YAT_Archivista at 2007-7-14 22:15:19 > top of Java-index,Core,Core APIs...
# 3
Many thanks for the helpful advice, that did the trick.
j.svazica at 2007-7-14 22:15:19 > top of Java-index,Core,Core APIs...