【发布时间】:2020-05-01 05:35:32
【问题描述】:
我有一个文本(例如"All Java programmers program good programs."),需要输出所有包含program 的单词。
Pattern pattern = Pattern.compile("program");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.start() + " " + extractWord(matcher.start(), text));
}
我可以写一个Pattern,它将整个找到诸如“程序员”之类的词作为Matcher结果吗?
我自己编写了extractWord 方法:
public static String extractWord(int start, String line) {
int n = 0;
while (start + n < line.length()) {
if (line.charAt(start + n) == ' ' || line.charAt(start + n) == '.') {
break;
} else {
n++;
}
}
return line.substring(start, start + n);
}
但我不喜欢这样做。
【问题讨论】: