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=]”
# 1 楼答案
我个人也会使用String类的^{} 方法
然而,不要想当然地认为你的字符串至少有30个字符长,我猜这可能是你问题的一部分:
这就利用了三元运算符,其中有一个布尔条件。因此,如果字符串短于30个字符,我们将使用整个字符串并避免
java.lang.StringIndexOutOfBoundsException
# 2 楼答案
改用
substring