Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式-捕获所有重复组_Java_Regex - Fatal编程技术网

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

Java 正则表达式-捕获所有重复组,java,regex,Java,Regex,我有如下字符串: @property.one@some text here@property.two@another optional text here etc 其中包含@.+?@字符串 我想通过一个regexp匹配将所有这些“变量”捕获到组中,但这似乎是不可能的,因为regexp在重复时只返回最后捕获的组 你是对的;大多数正则表达式风格(包括Java)都不允许访问重复捕获组的单个匹配项。(Perl 6和.NET确实允许这样做,但这对您没有帮助) 你还能做什么 Pattern regex =

我有如下字符串:

@property.one@some text here@property.two@another optional text here etc
其中包含
@.+?@
字符串


我想通过一个regexp匹配将所有这些“变量”捕获到组中,但这似乎是不可能的,因为regexp在重复时只返回最后捕获的组

你是对的;大多数正则表达式风格(包括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@
等。

如果您知道分隔符将是
@
,那么为什么不直接使用该方法(
string.split('@')
)呢?

请小心,您可能想要
[^]+
而不是
@
。我忘了输入正确的版本,应该是“@.+?@它不是分隔符,它是属性/占位符的开始/结束“标记”。在这种情况下,您不能执行
拆分吗?
无论如何,遍历生成的数组并捕获属性名称和可选文本?在下面的示例中,您如何知道哪个是属性,哪个是文本:”@property@text“和”text@property". Split为您提供[“属性”、“文本”或[“文本”、“属性”]。