Regex fails to capture all groups

后端 未结 5 1220
北荒
北荒 2021-01-29 01:36

Using java.util.regex (jdk 1.6), the regular expression 201210(\\d{5,5})Test applied to the subject string 20121000002Test only captures <

相关标签:
5条回答
  • 2021-01-29 02:05

    Change the line

    for(int i = 1; i<m1.groupCount(); i++){     
    

    to

    for(int i = 1; i<=m1.groupCount(); i++){      //NOTE THE = ADDED HERE    
    

    It now works as a charm!

    0 讨论(0)
  • 2021-01-29 02:07
    for (int i = 1; i <= m1.groupCount(); i++) { 
                       ↑
                  your problem
    
    0 讨论(0)
  • 2021-01-29 02:08

    m1.groupCount() returns the number of capturing groups, ie. 1 in your first case so you won't enter in this loop for(int i = 1; i<m1.groupCount(); i++)

    It should be for(int i = 1; i<=m1.groupCount(); i++)

    0 讨论(0)
  • 2021-01-29 02:14

    the regular expression "201210(\d{5,5})Test" applied to the subject string "20121000002Test" only captures group(0) and does not capture group(1)

    Well I can say I didn't read the manual either but if you do it says for Matcher.groupCount()

    Returns the number of capturing groups in this matcher's pattern. Group zero denotes the entire pattern by convention. It is not included in this count.

    0 讨论(0)
  • 2021-01-29 02:30

    From java.util.regex.MatchResult.groupCount:

    Group zero denotes the entire pattern by convention. It is not included in this count.

    So iterate through groupCount() + 1.

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