Regular Expression - Capturing all repeating groups

后端 未结 2 912
无人共我
无人共我 2020-12-01 17:11

I have strings like below:

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

which contains @.+?@ strin

相关标签:
2条回答
  • 2020-12-01 17:36

    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.

    0 讨论(0)
  • 2020-12-01 17:51

    If you know that the separator will be @, then why not just use the split method (string.split('@'))?

    0 讨论(0)
提交回复
热议问题