2012-02-13 64 views
1

我有以下字符串的字符串Java的正则表达式:解析与两个匹配子

任务BLABLA @ {}任务id “@ {} BLABLA.title”

,并希望从中提取所有的占位符它。

占位符是@ {taskId}和@ {BLABLA.title}。

我使用以下代码:

final Pattern pattern = Pattern.compile(".*(\\@\\{.*?\\}).*"); 
final Matcher matcher = pattern.matcher(this.text); 

while (matcher.find()) 
{ 
    final String placeholder = matcher.group(1); 
    this.placeholders.add(placeholder); 
} 

的问题是,在与一个以上的占位符线(如上面示出)检测到仅第一个占位符。

又如:

任务BLABLA @ {}任务id “@ {} BLABLA.title”{启动@ {}的startDateTime

任务BLABLA2 “文本”{分配RBLABLA2努力@ {BLABLA2。努力} }}

在本文中,上面的代码检测

  1. @ {BLABLA.title}
  2. @ {的startDateTime}
  3. @ {BLABLA2.effort}

如果删除@ {BLABLA.title},然后@ {的TaskID}被检测。

我应该如何修改代码,以便在上例中检测到所有占位符(@ {taskId},@ {BLABLA.title},@ {startDateTime},@ {BLABLA2.effort})?

回答

2

删除表达式开头和结尾的贪婪通配符匹配(.*)。然后,您的正则表达式将阅读:

"(\\@\\{.*?\\})" 

除去已经通配符,也可以省略分组:

"\\@\\{.*?\\}" 
1

删除前导和结尾的*,因为他们吃了你的整个字符串。在你的循环中用m.group(0)代替m.group(1)

1
//Another way to solve problem 
String task = "task [email protected]{taskId} \"@{BLABLA.title}"; 
String splitBy = "\\@\\{"; 
String[] splitted = task.split(splitBy); 
Set<String> placeHolders = new HashSet<String>(); 
for(String split : splitted) { 
    int startOf = split.indexOf("}"); 
    if(startOf != -1) { 
    placeHolders.add(split.substring(0, startOf)); 
    } 
} 
System.out.println("place holders are " + placeHolders);