2012-03-19 131 views
2

我需要匹配條目,如{@x anything},像a b c 1 225 {@x anything here1} test test {@x blabla} xyz test {@x any characters here}這樣的字符串。我試圖\{(@x ([^\}].*\w+(\.*)\s*)*)\}到目前爲止,但是這是不是真的我想要的,我有點堅持:(Java - 正則表達式 - 組分隔

所以,應該讓:

anything here1

blabla

any characters here

+0

那麼,有什麼問題?你試過什麼了? – AlexR 2012-03-19 15:29:10

+2

我提到'我嘗試過......迄今爲止' – 2012-03-19 15:30:27

回答

1

試試這個: 「({@x([^ {] *)})」

String string = "a b c 1 225 {@x anything = here1} test test {@x bl** #abla} xyz test {@x any characters here}";   
    String regexp = "(\\{\\@x ([^\\{]*)\\})"; 
    Pattern pattern = Pattern.compile(regexp); 
    Matcher matcher = pattern.matcher(string); 
    while (matcher.find()){ 
     System.out.println(matcher.group(2)); 
    } 
+0

謝謝,@yggdraa。 – 2012-03-19 15:49:35

+0

是否有效?我剛剛編輯它與第二組匹配:) – yggdraa 2012-03-19 15:52:55

+0

它工作正常:) – Sergiu 2012-03-19 15:53:44

2

好爲了提取所有來自該結構的組,您可以從下面開始:

{@x [a-zA-Z0-9 ]+} 

從這一點開始,只需刪除請求的字符串的標題和結尾,並且您應該具有所需的輸出。

編輯:

我已經更新了正則表達式位:

{@x [\w= ]+} 
+0

我可能需要在那裏有特殊字符,例如等號('=')。 – 2012-03-19 15:37:49

+0

我想他說他可以有多個特殊字符(不僅是等號)。 – Sergiu 2012-03-19 15:42:57

1

另一個嘗試:

String input="a b c 1 225 {@x anything here1} test test {@x blabla} xyz test {@x any characters here}"; 
    String pattern = "\\{@x [(\\w*)(\\s*)]*\\}"; 
    for(String s: input.split(pattern)){ 
     System.out.println(s); 
    } 

\ W * =任何字(AZ,AZ,0-9); * = 0或更多

\ s * =空格; * = 0或更多

[] * - 重複組。

1

這應做到:

String string = "a b c 1 225 {@x anything here1} test test {@x blabla} xyz test {@x any characters here}"; 
String regexp = "\\{\\@x ([^\\}]*)\\}"; 
Pattern pattern = Pattern.compile(regexp); 
Matcher matcher = pattern.matcher(string); 
while (matcher.find()){ 
    System.out.println(matcher.group(1)); 
} 

\ {\ @ X - 匹配器啓動。

([^ \}] *) - 匹配點兒除了最終捲曲(}​​),並把該組中的(1)

\} - 結束捲曲

匹配,那麼您搜索並減去你的組。

1

要在模式告訴「人物‘{’和‘}’之間的最小匹配」,因此您可以使用該模式是在我看來:

final String string = "a b c 1 225 {@x anything = here1} test test {@x bl** #abla} xyz test {@x any characters here}"; 
    final Pattern pattern = Pattern.compile("\\{@x (.*?)\\}"); // <-- pattern 
    final Matcher matcher = pattern.matcher(string); 
    while (matcher.find()) 
     System.out.println(matcher.group(1)); 

?.*?的做法剛好那。