我希望在两个单词之间得到所有文本.例如:
String Testing="one i am here fine two one hope your are also fine two one ok see you two";
Run Code Online (Sandbox Code Playgroud)
从上面的字符串中,我想获取数组中"one"和"two"之间的单词:
我的结果应该像这样存储在数组中:
String result[1] = i am here fine
String result[2] = hope your are also fine
String result[3] = ok see you
Run Code Online (Sandbox Code Playgroud)
在java中怎么办?
提前致谢
String input = "one i am here fine two one hope your are also fine two one ok see you two;";
Pattern p = Pattern.compile("(?<=\\bone\\b).*?(?=\\btwo\\b)");
Matcher m = p.matcher(input);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group());
}
Run Code Online (Sandbox Code Playgroud)
这将创建"一"和"两"之间所有文本的列表.
如果你想要一个不使用lookaheads/lookbehinds的简单版本,请尝试:
String input = "one i am here fine two one hope your are also fine two one ok see you two;";
Pattern p = Pattern.compile("(\\bone\\b)(.*?)(\\btwo\\b)");
Matcher m = p.matcher(input);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group(2));
}
Run Code Online (Sandbox Code Playgroud)
注意: Java数组从零开始而不是基于一个,因此在您的示例中,第一个结果将result[0]
不是result[1]
.在我的解决方案中,第一场比赛是在matches.get(0)
.