2012-03-19 104 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)); 

?.*?的做法刚好那。