代码改变世界

正则表达式m.find() and m.group()

2021-09-11 00:34  钱先生  阅读(254)  评论(0编辑  收藏  举报

问题:

在用正则表达式截取字符串时,要先执行m.find(),再输出m.group()。否则会返回"No match found" 异常,为什么?

 

代码:

public static String truncateSentence(String s,int k) {
		String regex = "(\\w+\\s{1})"+"{"+ k + "}";
		Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(s);
        //throw "No match found" exception if m.find() is not executed.
        //m.find();
        return m.group();
	}