1
import java.util.regex.*;

public class Regex2 {

    public static void main(String[] args) {
        Pattern p = Pattern.compile("\\d*");
        Matcher m = p.matcher("ab34ef");
        boolean b = false;
        while ( m.find()) {
            System.out.print(m.start() + m.group());
        }
    }
}

Why this code produce output: 01234456

falsetru
  • 357,413
  • 63
  • 732
  • 636
Salahin Rocky
  • 415
  • 9
  • 18

3 Answers3

2

@vks is right: If you are using \\d* it works on each characters:

Index: char = matching:
    0: 'a'  = "" because no integer
    1: 'b'  = "" because no integer
    2: '3'  = "34" because there is two integer between index [2-3]
       '4'    is not checked because the index has been incremented in previous check.
    4: 'e'  = ""
    5: 'f'  = "" because no integer
    6: ''   = "" IDK

It produce 0, "", 1, "", 2, "34", 4, "", 5, "", 6, "" = 01234456 (that's why you got it).

If you use \\d+ only the groups with one or more integer will match.

Nemolovich
  • 391
  • 2
  • 12
1
\d* means integer 0 or more times.So an empty string between a and b ,before a ...those are also

matched.Use `\d+` to get correct result.

See demo.

https://www.regex101.com/r/fG5pZ8/25

vks
  • 67,027
  • 10
  • 91
  • 124
0

Because \\d* indicates zero or more digits.

As,

enter image description here

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55