Java 使用正则表达式查找所有可能发生的事件

Java 使用正则表达式查找所有可能发生的事件,java,regex,string,Java,Regex,String,我有一个字符串,如下所示,例如: i installed apache2 and when i transfered the httpd.conf to the new structure 我正在尝试查找正则表达式I.*结构的所有匹配项 我的代码如下所示 List<String> matches = new ArrayList<>(); Pattern p = Pattern.compile("i.*structure", Pattern.MULTILINE|Patte

我有一个字符串,如下所示,例如:

i installed apache2 and when i transfered the httpd.conf to the new structure
我正在尝试查找正则表达式
I.*结构的所有匹配项

我的代码如下所示

List<String> matches = new ArrayList<>();
Pattern p = Pattern.compile("i.*structure", Pattern.MULTILINE|Pattern.DOTALL);
Matcher m = p.matcher(text);
while (m.find()) {
  matches.add(m.group());
}
System.out.println(matches);
我所期望的是:

[i installed apache2 and when i transfered the httpd.conf to the new structure, 
 installed apache2 and when i transfered the httpd.conf to the new structure, 
 i transfered the httpd.conf to the new structure]
谁能解释一下我做错了什么

感谢和问候

您可以使用捕获重叠匹配

Pattern p = Pattern.compile("(?s)(?=(i.*?structure))");
前瞻不会“使用”字符串上的任何字符

向前看之后,正则表达式引擎返回到它开始查看的字符串上的相同位置。从那里,它可以再次开始匹配

注意:
*
是一个运算符,意味着它将尽可能多地匹配,并且仍然允许正则表达式的其余部分匹配。您希望使用
*?
代替表示“零或更多-最好尽可能少”的非贪婪匹配


我忘了提到,字符串可能是另一个字符串的内容,因此
I
结构可能不是字符串的左右分隔符!
Pattern p = Pattern.compile("(?s)(?=(i.*?structure))");