java 正则表达式查找某段字符串中所有小写字母开头的单词并统计次数,按出现次数排序

这段Java代码展示了如何使用正则表达式查找字符串中所有以小写字母开头的单词,并统计它们出现的次数,然后按照出现次数进行排序。通过Matcher和Pattern类处理字符串,并使用ConcurrentHashMap存储结果,最后通过sortMap方法进行排序输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Groups {
    static public final String POEM=
        "Twas brilling,and the slithy toves\n"+
        "Did gyre and gimble in the wabe.\n"+
        "All mimsy were the borogoves,\n"+
        "And the mome raths outgrabe.\n\n"+
        "Beware the Jabberwock,my sin,\n"+
        "The jaws that bite,the claws that catch.\n"+
        "Beware the Jubjub bird,and shun\n"+
        "The frumious Bandersnatch.";
    public static void  main(String[] args){
        Matcher m=
//                Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(POEM);//取后三个单词
//                Pattern.compile("\\b[A-Z]\\w+").matcher(POEM);//所有大写单词
//                Pattern.compile("\\b\\p{Upper}\\w+").matcher(POEM);//所有大写单词
//                Pattern.compile("\\b\\p{Lower}\\w+").matcher(POEM);//所有小写单词
                Pattern.compile("\\b[a-z]\\w+").matcher(POEM);//所有小写单词
        Map<String,Integer> strMap=new ConcurrentHashMap<String, Integer>();
        while(m.find()){
            if(strMap.get(m.group())==null)
                strMap.put(m.group(), 1);
            else
                strMap.put(m.group(), strMap.get(m.group())+1);
        }
        strMap=sortMap(strMap);
        for(String danci:strMap.keySet())
            System.out.println(danci+"="+strMap.get(danci));
    }
     public static Map sortMap(Map oldMap) {  
            ArrayList<Map.Entry<Character, Integer>> list = new ArrayList<Map.Entry<Character, Integer>>(oldMap.entrySet());  
            Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() { 
                public int compare(Entry<java.lang.Character, Integer> arg0,  
                        Entry<java.lang.Character, Integer> arg1) {  
                    return arg1.getValue() - arg0.getValue();  
                }  
            });  
            Map newMap = new LinkedHashMap();  
            for (int i = 0; i < list.size(); i++) {  
                newMap.put(list.get(i).getKey(), list.get(i).getValue());  
            }  
            return newMap;  
      } 
}
运行结果:
the=7
and=3
that=2
slithy=1
bite=1
in=1
frumious=1
catch=1
mome=1
sin=1
mimsy=1
my=1
bird=1
toves=1
shun=1
raths=1
jaws=1
wabe=1
brilling=1
were=1
outgrabe=1
gimble=1
borogoves=1
gyre=1
claws=1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值