[英]Regular Expression - Capturing all repeating groups
I have strings like below: 我有如下字符串:
@property.one@some text here@property.two@another optional text here etc
which contains @.+?@
strings inside. 其中包含
@.+?@
字符串。
I'd like to capture all these "variables" into groups via one regexp matching but it seems like it's not possible as regexp returns only last captured group while repeating. 我想通过一个正则表达式匹配将所有这些“变量”捕获到组中,但似乎不可能因为正则表达式在重复时仅返回最后捕获的组。
You're right; 你是对的; most regex flavors, Java included, do not allow access to individual matches of a repeated capturing group.
包含Java的大多数正则表达式都不允许访问重复捕获组的单个匹配。 (Perl 6 and .NET do allow this, for the record, but that's not helping you).
(对于记录,Perl 6和.NET确实允许这样做,但这对你没有帮助)。
What else can you do? 你还能做什么?
Pattern regex = Pattern.compile("@[^@]+@");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
// matched text: regexMatcher.group()
// match start: regexMatcher.start()
// match end: regexMatcher.end()
}
That will capture @property.one@
, @property.two@
etc. one by one. 这将逐一捕获
@property.one@
, @property.two@
等。
如果您知道分隔符将是@
,那么为什么不使用split方法( string.split('@')
)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.