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

Java 如何正确使用Matcher检索字符串的前30个字符?,java,string,matcher,Java,String,Matcher,我的目标是返回用户输入字符串的前30个字符,并在电子邮件主题行中返回 我目前的解决方案是: Matcher matcher = Pattern.compile(".{1,30}").matcher(Item.getName()); String subject = this.subjectPrefix + "You have been assigned to Item Number " + Item.getId() + ": "

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

我目前的解决方案是:

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

为matcher返回的是“java.util.regex.matcher[pattern=.{1,30}region=0,28 lastmatch=]”

改用
子字符串

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

如果您确实需要使用
匹配器
,请尝试:

Matcher matcher = Pattern.compile(".{1,30}").matcher("123456789012345678901234567890");
if (matcher.find()) {
    String subject = matcher.group(0);
}
但最好使用
子字符串
方法:

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

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

如果您确实想使用
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;
}

我个人也会使用String类的方法

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

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

这就利用了三元运算符,其中有一个布尔条件,然后是和。因此,如果您的字符串小于30个字符,我们将使用整个字符串并避免出现
java.lang.StringIndexOutOfBoundsException

您听说过substring方法吗?您是否考虑过使用Item.getName().substring(0,30)?您可以找到许多关于如何在java中使用正则表达式模式的教程。对于这个任务,您甚至不需要RegEx的强大功能。这里有一个教程链接:这能回答你的问题吗?这回答了你的问题吗?非常感谢。我不知道substring方法。
    String itemName = "lorem ipsum";
    String itemDisplayName = itemName.substring(0, itemName.length() < 30 ? itemName.length() : 30);
    System.out.println(itemDisplayName);