有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何正确使用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 + "...";

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


共 (2) 个答案

  1. # 1 楼答案

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

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

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

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

  2. # 2 楼答案

    改用substring

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