简体   繁体   中英

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. (Perl 6 and .NET do allow this, for the record, but that's not helping you).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM