The pattern "\\d*"
matches 0 or more digits. Same stands for ".*"
. It matches 0 or more occurrence of any character except newline.
The last match that you get is the empty string at the end of your string, after "b"
. The empty string satisfies the pattern \\d*
. If you change the pattern to \\d+
, you'll get expected result.
Similarly, the pattern .*
matches everything from first character to last character. Thus it first matches "a1b"
. After that the cursor is after b
: "a1b|"
. Now, matcher.find()
again runs, and finds a zero-length string at the cursor, which satisifies the pattern .*
, so it considers it as a match.
The reason why it gives expected output with "^.*$"
is that the last empty string doesn't satisfy the ^
anchor. It is not at the beginning of the string, so it fails to match.