I am trying to find a number of Occurrence of each character on the given string.
t=2 e=1 s=1 i=1 n=1 g=1
T=0 e=0 s=0 t=0 i=0 n=0 g=0
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.
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