我有以下字符串
task BLABLA@{taskId} "@{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);
}
问题在于,在包含多个占位符的行中(如上所示),它仅检测到第一个占位符。
另一个例子:
task BLABLA@{taskId} "@{BLABLA.title}" { start @{startDateTime}
task BLABLA2 "Text" { allocate RBLABLA2 effort @{BLABLA2.effort} } }
在这段文字中,上面的代码检测
- @{BLABLA.title}
- @{startDateTime}
- @{BLABLA2.effort}
如果我删除@{BLABLA.title},则会检测到@{taskId}。
我应该如何修改代码,以便在最后一个示例中检测到所有占位符(@{taskId}、@{BLABLA.title}、@{startDateTime}、@{BLABLA2.effort})?
最佳答案
删除表达式开头和结尾的贪婪通配符匹配 (.*
)。您的正则表达式将显示为:
"(\\@\\{.*?\\})"
删除通配符后,您还可以省略分组:
"\\@\\{.*?\\}"
关于Java 正则表达式 : Parsing a string with two matching substrings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9262557/