正则表达式 - 捕获所有重复组 [英] Regular Expression - Capturing all repeating groups

查看:107
本文介绍了正则表达式 - 捕获所有重复组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下字符串:

@property.one@some text here@property.two@another optional text here etc

包含 @。+?@ 里面的字符串

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

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.

推荐答案

你是对的;包含Java的大多数正则表达式风格不允许访问重复捕获组的单个匹配。 (Perl 6和.NET确实允许这样做,记录,但这对你没有帮助。)

You're right; most regex flavors, Java included, do not allow access to individual matches of a repeated capturing group. (Perl 6 and .NET do allow this, for the record, but that's not helping you).

你还能做什么?

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 @ 等一个接一个。

That will capture @property.one@, @property.two@ etc. one by one.

这篇关于正则表达式 - 捕获所有重复组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆