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 + "...";
匹配器返回的是“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;
}
推荐阅读
- rtrt - 用于数组输入参数的 Rtrt 存根
- r - 如何改进 R 中的 survrec 图?
- css - 如何使用 Bootstrap 4 使帮助文本为 100% 宽度但输入字段不是
- android - facebook原生adview替换recyclerview的原始项目
- user-interface - 从连接读取更新多行条目
- python - 如何将 [PRIMARY] 上的 SqlServer 转换为 Sqlalchemy 模型?
- c# - 带有 SoundTouch BPMDetect 的 NAudio WaveIn 的 C# 示例
- python - 如何在熊猫中拆分和存储数据框中的数据
- c++ - OPENSSL 将二进制字节转换为 SHA256 C++
- random - 我想出了这两种方法来获得 5 个唯一的随机数。哪个更好/更有效?有没有其他更有效的方法?