如何正确使用Matcher检索字符串的前30个字符?

问题描述

我的目标是返回用户输入的String的前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 =]”

解决方法

我认为最好使用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;
}
,

好吧,如果您确实需要使用Matcher,请尝试:

Matcher matcher = Pattern.compile(".{1,30}").matcher("123456789012345678901234567890");
if (matcher.find()) {
    String subject = matcher.group(0);
}

但是最好使用substring方法:

String subject = "123456789012345678901234567890".substring(0,30);
,

我个人也将使用String类的substring方法。

但是,不要认为您的字符串至少有30个字符长,我想这可能是您的问题的一部分:

    String itemName = "lorem ipsum";
    String itemDisplayName = itemName.substring(0,itemName.length() < 30 ? itemName.length() : 30);
    System.out.println(itemDisplayName);

这利用了三元运算符(如果您具有布尔条件),则使用else。因此,如果您的字符串少于30个字符,我们将使用整个字符串,并避免使用java.lang.StringIndexOutOfBoundsException

,

改为使用substring

String str = "....";
String sub = str.substring(0,30);