How to count uppercase, lowercase, special characters, and numeric values using RegEx in Java

1 Answer

0 votes
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CountCharacters {

    public static int countMatches(String text, String regex) {
        Matcher m = Pattern.compile(regex).matcher(text);
        int count = 0;
        while (m.find()) {
            count++;
        }
        
        return count;
    }

    public static void main(String[] args) {
        String s = "Programming&AI@2026!";

        int uppercase = countMatches(s, "[A-Z]");
        int lowercase = countMatches(s, "[a-z]");
        int digits    = countMatches(s, "\\d");
        int special   = countMatches(s, "[^A-Za-z0-9]");

        System.out.println("Uppercase: " + uppercase);
        System.out.println("Lowercase: " + lowercase);
        System.out.println("Digits: " + digits);
        System.out.println("Special characters: " + special);
    }
}


/*
run:

Uppercase: 3
Lowercase: 10
Digits: 4
Special characters: 3

*/

 



answered Feb 20 by avibootz

Related questions

...