【发布时间】:2011-08-15 08:28:47
【问题描述】:
我想使用 java 提取某些两个单词之间的子字符串。
例如:
This is an important example about regex for my work.
我想提取“an”和“for”之间的所有内容。
到目前为止我所做的是:
String sentence = "This is an important example about regex for my work and for me";
Pattern pattern = Pattern.compile("(?<=an).*.(?=for)");
Matcher matcher = pattern.matcher(sentence);
boolean found = false;
while (matcher.find()) {
System.out.println("I found the text: " + matcher.group().toString());
found = true;
}
if (!found) {
System.out.println("I didn't found the text");
}
效果很好。
但我还想做两件事
如果句子是:
This is an important example about regex for my work and for me.我想提取到第一个“for”即important example about regex有时我想将模式之间的单词数限制为 3 个单词,即
important example about
有什么想法吗?
【问题讨论】:
-
你想要模式只匹配 'an' 和 'for' 之间只有 3 个单词,还是只需要 3 个单词而不考虑匹配中的单词数?跨度>
-
@Dragon8:我只想要3个单词,不管匹配的单词数。
-
好的,然后你可以用
someString.split(" ")分割比赛。它返回一个字符串数组,每个位置都是匹配中的一个单词。