【问题标题】:How do I properly use Matcher to retrieve first 30 chars of a String?如何正确使用 Matcher 检索字符串的前 30 个字符?
【发布时间】:2021-01-02 08:29: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=]”

【问题讨论】:

标签: java string matcher


【解决方案1】:

我觉得用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;
}

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 谢谢。我不知道 substring 方法。
    【解决方案3】:

    好吧,如果你真的需要使用Matcher,那就试试吧:

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

    但最好使用substring方法:

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

    【讨论】:

      【解决方案4】:

      请改用substring

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

      【讨论】:

        猜你喜欢
        • 2012-09-30
        • 1970-01-01
        • 1970-01-01
        • 2012-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        相关资源
        最近更新 更多