2014-09-11 64 views
2

這是我想要處理的輸入。我想提取operation屬性的值:如何在java中正確地逃避這個正則表達式模式?

<h:outputLink value="#" id="temp_solution"> 
    <rich:componentContro 
     for="panel" 
     attachTo="temp_solution" 
     operation="show" 
     event="onclick"/> 
</h:outputLink> 

隨着online regex tester的幫助下,我想出了下面的正則表達式

(?<=operation=")(\w+)(?=") 

是有點更有活力,我換成operation%s所以我可以在不同的情況下使用這個模板。但是,我遇到了一個問題,而試圖測試我的「創造」一個小的測試程序的幫助:

public class Main { 
    private static final String INPUT = "<h:outputLink value=\"#\" id=\"temp_solution\">\n" 
     + " <rich:componentControl \n" 
     + "  for=\"panel\" \n" 
     + "  attachTo=\"temp_solution\" \n" 
     + "  operation=\"show\"" 
     + "  event=\"onclick\"/> \n" 
     + "</h:outputLink>"; 

    private static final String REGEX_TEMPLATE = "(?<=%s=\")(\\w+)(?=\")"; 

    public static void main(String[] args) throws IOException { 
    final String actualRegex = String.format(REGEX_TEMPLATE, "operation");  
    final Pattern pattern  = Pattern.compile(actualRegex); 
    final Matcher matcher  = pattern.matcher(INPUT); 

    System.out.println("Regex: " + pattern);  
    System.out.println(matcher.matches() ? matcher.group(0) : "Nothing found"); 
    } 
} 

輸出:

Regex: (?<=operation=")(\w+)(?=") 
Nothing found 



即使雙重逸出裏面的正則表達式我代碼:

private static final String REGEX_TEMPLATE = "(?<=%s=\\\")(\\\\w+)(?=\\\")"; 

沒有幫助:

Regex: (?<=operation=\")(\\w+)(?=\") 
Nothing found 

請給我一些建議。

回答

5

你的正則表達式沒有錯。但是,它與整個輸入不匹配,因此您不能使用matches()。將其更改爲find(),它只是試圖找到匹配的序列:

System.out.println(matcher.find() ? matcher.group(0) : "Nothing found"); 
+0

哇,謝謝,我剛剛成爲有思想的東西約迷戀正則表達式不正確。沒想到看看它是如何使用的。我會盡快接受你的回答(有時間限制)。 – ifloop 2014-09-11 11:23:02

1

嘗試正則表達式是這樣的:

(?<=operation=\")(\w+) 

demo

+0

@Keppil回答,我的正則表達式沒問題,但我用它的方式是錯誤的。無論如何謝謝你試圖幫助我! – ifloop 2014-09-11 11:26:51

+0

@ifLoop - 始終與*正確*答案.. :)。我編輯了我的正則表達式和演示,選擇不帶引號。 :P – TheLostMind 2014-09-11 11:29:24

+1

是的,它做我想要的,並且稍微短一些。我會給你+1這個整潔的加法:) – ifloop 2014-09-11 11:32:17