首页 > 解决方案 > 如何正确使用 Matcher 检索字符串的前 30 个字符?

问题描述

我的目标是返回用户输入字符串的前 30 个字符,并将其返回到电子邮件主题行中。

我目前的解决方案是这样的:

 Matcher matcher = Pattern.compile(".{1,30}").matcher(Item.getName());
    String subject = this.subjectPrefix + "You have been assigned to Item Number " + Item.getId() + ": " + matcher + "...";

匹配器返回的是“java.util.regex.Matcher[pattern=.{1,30} region=0,28 lastmatch=]”

标签: javastringmatcher

解决方案


我认为最好使用String.substring()

public static String getFirstChars(String str, int n) {
    if(str == null)
        return null;
    return str.substring(0, Math.min(n, str.length()));
}

如果您真的想使用regexp,那么这是一个示例:

public static String getFirstChars(String str, int n) {
    if (str == null)
        return null;

    Pattern pattern = Pattern.compile(String.format(".{1,%d}", n));
    Matcher matcher = pattern.matcher(str);
    return matcher.matches() ? matcher.group(0) : null;
}

推荐阅读