正则表达式 - 捕获所有重复组

Krz*_*lny 9 java regex

我有如下字符串:

@property.one@some text here@property.two@another optional text here etc
Run Code Online (Sandbox Code Playgroud)

其中包含@.+?@字符串.

我想通过一个正则表达式匹配将所有这些"变量"捕获到组中,但似乎不可能因为正则表达式在重复时仅返回最后捕获的组.

Tim*_*ker 17

你是对的; 包含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()
} 
Run Code Online (Sandbox Code Playgroud)

这将捕获@property.one@,@property.two@等一个接一个.