如何使用Pattern Class(Regex)计算java字符串中每个字符的出现次数 [英] 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.
- 预期输出:
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
- Expected output:
t=2 e=1 s=1 i=1 n=1 g=1
- Current output:
T=0 e=0 s=0 t=0 i=0 n=0 g=0
代码:
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);
}
有很多方法可以做到这一点,但我只是在寻找Regex,所以我们如何通过使用Regex实现这一目标。任何帮助,将不胜感激。在此先感谢。
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.
推荐答案
如果您使用的是Java8 +,则无需正则表达式来解决您的问题,您只需使用:
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()));
输出
{t=2, e=1, s=1, i=1, n=1, g=1}
编辑
Edit
mmm,这种情况下的模式没用我不建议使用在这个问题中,作为使用Pattern和Java9 +结果的替代解决方案,你可以使用:
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));
输出
t = 2
e = 1
s = 1
i = 1
n = 1
g = 1
这篇关于如何使用Pattern Class(Regex)计算java字符串中每个字符的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!