2017-09-21 36 views
0

嘗試寫一些代碼stylechecker並在Java中使用backrefrences的多正則表達式......這裏的正則表達式是什麼樣子Backrefrences在多java的正則表達式

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

基本上,想找到我的代碼中的工廠類的第一個實例。我的示例代碼如下所示:

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

// other nonsense 

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

我預計比賽將在@Import聲明SomeFactory.class,但它不挑這件事......有什麼建議?

+1

編譯模式時,請勿忘記使用'Pattern.DOTALL'標誌。 – Zefick

+1

你能添加你的預期比賽嗎? –

回答

1

你可以使用這個表達式:

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

在Java中使用:

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

RegEx Demo

捕獲組#1 SomeFactory.class進口線後捕獲組#2是SomeFactory.class@Import一行。

+0

@backwardsboy:讓我知道如果這不起作用。 – anubhava