我有以下字符串:
@property.one@some text here@property.two@another optional text here etc
这段文本包含着 @.+?@
字符串。
我想通过一个正则表达式匹配捕获所有这些 "变量" 到分组里,但是看起来不可能,因为正则表达式只返回最后一次重复匹配捕获的分组。
你说得对;大多数正则表达式引擎,包括Java在内,都不允许访问重复捕获组的单个匹配项。(值得一提的是,Perl 6和.NET允许这样做,但这并不能帮到你)。
还有什么其他办法呢?
Pattern regex = Pattern.compile("@[^@]+@");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
// matched text: regexMatcher.group()
// match start: regexMatcher.start()
// match end: regexMatcher.end()
}
这将一个一个地捕获@property.one@
,@property.two@
等。
如果你知道分隔符是 @
,为什么不直接使用 split 方法 (string.split('@')
)?
split
,遍历结果数组并捕获属性名称和可选文本,对吧? - user554546
@[^@]+@
而不是@.+@
。 - sidyll