正则表达式 – 捕获所有重复组
我有如下字符串:
@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('@')
)?