Bunny Rabbit
Bunny Rabbit

Reputation: 8411

How to match any number of capital letters?

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

Answers (2)

basiljames
basiljames

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

Vikdor
Vikdor

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

Related Questions