Java regex capture not working

后端 未结 4 1157
逝去的感伤
逝去的感伤 2020-12-22 11:49

I have a regular expression:

l:([0-9]+)

This should match this string and return three captures (according to Rubular)

\"l:         


        
相关标签:
4条回答
  • 2020-12-22 12:33

    Matcher.find() returns false when there are no more matches, so you can do a while loop whilst getting and processing each group. For example, if you want to print all matches, you can use the following:

        Matcher m;
        Pattern p = Pattern.compile("l:([0-9]+)");
        m = p.matcher("l:32, l:98, l:1234");
    
        while (m.find()) {
            System.out.println(m.group());
        }
    
    0 讨论(0)
  • 2020-12-22 12:41

    Calling Matcher.find finds the next instance of the match, or returns false if there are no more. Try calling it three times and see if you have all your expected groups.

    To clarify, m.group(1) is trying to find the first group expression in your regular expression. You only have one such group expression in your regex, so group(2) would never make sense. You probably need to call m.find() in a loop until it returns false, grabbing the group result at each iteration.

    0 讨论(0)
  • 2020-12-22 12:44

    I think it needs to be

    Pattern p ...
    Matcher m = p.matcher(...);
    int count = 0;
    
    while(m.find()) {
        count++;
    }
    System.out.println(count);
    

    find looks for the next match, so using a while loop will find all matches.

    0 讨论(0)
  • 2020-12-22 12:47

    If input string format is fixed you could use following regex

    "l:32, l:98, l:234".split("(, )?l:")
    

    Output

    [, 32, 98, 234]
    
    0 讨论(0)
提交回复
热议问题