多行java正则表达式中的反引用
正在尝试为某些代码编写样式检查器,并在Java中为多行正则表达式使用反引用。。。下面是正则表达式的样子多行java正则表达式中的反引用,java,regex,backreference,Java,Regex,Backreference,正在尝试为某些代码编写样式检查器,并在Java中为多行正则表达式使用反引用。。。下面是正则表达式的样子 *导入com.+([a-zA-Z]+工厂\.class.*\\1.* 基本上,我希望在代码中找到工厂类的第一个实例。我的示例代码如下所示: import com.sample.OtherClass; import com.sample.cool.SomeFactory.class; // other nonsense @Import(clazz = SomeFactory.class) /
*导入com.+([a-zA-Z]+工厂\.class.*\\1.*
基本上,我希望在代码中找到工厂类的第一个实例。我的示例代码如下所示:
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).*(\1)
在Java使用中:
final String regex = "(?s)import\\s+com.+?\\.([a-zA-Z]+Factory\\.class).*(\\1)";
捕获的组#1是导入行之后的
SomeFactory.class
,捕获的组#2是导入行之后的SomeFactory.class
。编译模式时不要忘记使用Pattern.DOTALL
标志。是否可以添加预期的匹配项?