【发布时间】:2015-04-12 07:32:44
【问题描述】:
我正在尝试获取给定字符串的“预告片”并将其作为值放入 HashMap。 'teaser' 我的意思是一个子字符串(最大长度 50 个字符)结束一个单词边界。
这是一个代码示例,展示了我是如何尝试这样做的:
import java.util.regex.*;
public class Test {
public static void main(String[] args) throws Exception {
final Pattern pattern = Pattern.compile("(^.{0,50}\b)");
final Matcher m = pattern.matcher(
"This is a long string that I want to find a shorter teaser for.");
if (m.find()) {
System.out.println("Found: " + m.group(1));
} else {
System.out.println("No match");
}
}
}
我希望它会打印出来:
Found: This is a long string that I want to find a
但它会打印:
No match
如果我单独测试这个正则表达式,它会做它应该做的 - 它找到一个最大长度为 50 个字符并在单词边界上结束的值子字符串。但是如果我调试它,m.find 总是给我一个错误。
任何想法如何解决这个问题? (我专注于获取预告片,而不是使用 Matcher.find() ;-))
【问题讨论】:
-
使用:
Pattern.compile("(^.{0,50}\\b)") -
按照 Anubhava 所说,在循环之外声明您的 pattern.compile。您不必每次都创建它们。
-
也感谢这个。。从所有循环中得到它。