Reputation: 8411
public static void main(String[] args) {
Pattern p = Pattern.compile("[A-Z]*");
Matcher matcher = p.matcher("CSE");
System.out.println(matcher.group());
}
why is the obove code raising an java.lang.IllegalStateException ? How can i match any number of capital letters?
Upvotes: 1
Views: 165
Reputation: 4847
You have to call matcher.matches();
before calling a matcher.group());
matcher.group()
give you the substring identified by the previous match.
Your patten should be [A-Z]+
. This will print all matches of capital letter sequences
public static void main(String[] args) {
Pattern p = Pattern.compile("[A-Z]+");
Matcher matcher = p.matcher("CSEsdsdWWERdfsdfSSEEfdD");
while (matcher.find()) {
System.out.println(matcher.group());
}
}
Upvotes: 1
Reputation: 24134
You need to call Matcher.find()
to initiate the regex matching process.
public static void main(String[] args)
{
Pattern p = Pattern.compile("[A-Z]*");
Matcher matcher = p.matcher("CSE");
while (matcher.find()) {
System.out.println(matcher.group());
}
}
Upvotes: 3