javaregexstringwhile-loop

How to count occurrence of each character in java string using Pattern Class(Regex)


I am trying to find a number of Occurrence of each character on the given string.

Code:

String str = "Testing";
int count = 0;

Pattern p = Pattern.compile("[a-zA-Z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);

while (m.find()) {
    if (m.group().equals(str)) {
        count++;
    }
    System.out.println(m.group() + "=" + count);
}

There are many ways of doing this but I am looking for Regex only, so how can we achieve that by using Regex. Any Help would be Appreciated. Thanks in advance.


Solution

  • No need for a regex to solve your problem, if you are using Java8+ you can just use :

    String input = "Testing";
    Map<String, Long> result = Arrays.stream(input.split(""))
            .map(String::toLowerCase)
            .collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
    

    outputs

    {t=2, e=1, s=1, i=1, n=1, g=1}
    

    Edit

    mmm, Pattern in this case is useless I don't advice to use it in this problem, as an alternative solution using Pattern with results from Java9+ you can use :

    String str = "Testing";
    Pattern.compile(".").matcher(str)
            .results()
            .map(m -> m.group().toLowerCase())
            .collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()))
            .forEach((k, v) -> System.out.println(k + " = " + v)); 
    

    Outputs

    t = 2
    e = 1
    s = 1
    i = 1
    n = 1
    g = 1