[英]Regular Expression - Capturing all repeating groups
我有如下字符串:
@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('@')
)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.