2012-11-12 45 views
5

我試圖找到以下正則表達式:Java和回顧後在正則表達式

匹配@[email protected]所有的世界究竟在何處WORD可以是任何文字都不過只是一個=之後。 我作了如下:
(?<==)#.*?#)其作品,但只有像[email protected]@@[email protected]= @[email protected]模式。
我也有興趣不是之後是=但無法弄清楚。
無論如何使用類似:(?<=\\s*=\\s*)#.*?#)但它不起作用。
任何想法?

注:奇怪,但是從here它說,可變長度的回顧後是在Java的支持,但是這並沒有給我一個例外

回答

0

這種模式等號一致,後跟一個可選的空間和包裹一個字in @ symbols:

Pattern pattern = Pattern.compile("= [email protected](.*)@"); 
Matcher matcher = pattern.matcher("[email protected]@"); 
if (matcher.matches()) { 
    System.out.println(matcher.group(1)); 
} 

// Prints: "WORD" 

除非我誤解了您希望完成的任務,否則無法看到後視的需要。然而,下面應該工作:

Pattern pattern = Pattern.compile("(?<== ?)@(.*)@"); 
Matcher matcher = pattern.matcher("= @[email protected]"); 
if (matcher.find()) { 
    System.out.println(matcher.group(1)); 
} 

// Prints: "WORD" 

否定模式,然後完成如下:

Pattern pattern = Pattern.compile("(?<!= ?)@(.*)@"); 
Matcher matcher = pattern.matcher("[email protected]@"); 
System.out.println(matcher.find()); 

// Prints: "false" 
1

如果您正在使用向後看,我假設你是在直接使用PatternMatcher,抓到乾淨的字("@[email protected]"而不是"= @[email protected]")。

如果情況確實如此,所有你需要做的就是內添加一個可選的白色空間的向後看:

(?<==\\s?)@.*[email protected]


下面是測試代碼,返回"@[email protected]"

Matcher m = Pattern.compile("(?<==\\s?)@.*[email protected]").matcher("= @[email protected]"); 
m.find(); 
System.out.println(m.group()); 
相關問題