多行 java 正则表达式中的反向引用

Backrefrences in multi-line java regex

尝试为一些代码编写样式检查器并在 Java 中为多行正则表达式使用反向引用...这就是正则表达式的样子

.*import com.+([a-zA-Z]+Factory\.class).*\1.*

基本上,想在我的代码中找到工厂的第一个实例 class。我的示例代码如下所示:

import com.sample.OtherClass;
import com.sample.cool.SomeFactory.class;

// other nonsense

@Import(clazz = SomeFactory.class)
// other nonsense

我预期的匹配项是 @Import 语句中的 SomeFactory.class,但它没有选择...有什么建议吗?

您可以使用这个正则表达式:

(?s)import\s+com.+?\.([a-zA-Z]+Factory\.class).*()

在Java中使用:

final String regex = "(?s)import\s+com.+?\.([a-zA-Z]+Factory\.class).*(\1)";

RegEx Demo

捕获组 #1 在导入行之后 SomeFactory.class,捕获组 #2 在 @Import 行之后 SomeFactory.class