Regex searches beyond string boundary

后端 未结 1 1062
有刺的猬
有刺的猬 2021-01-21 05:16

The code is given below:

import java.util.regex.*;

public class RegEx {

    public static void main(String[] args) {

        Pattern p = Pattern.compile(\"\\\         


        
相关标签:
1条回答
  • 2021-01-21 05:56

    You have 6 indices returned because there are 6 matches here since \d* can match an empty string. There is always an empty string before each character in an input string, because the regex engine is processing text at each position looking for boundaries or specific characters.

    Here is the visualization:

    enter image description here

    Here, the engine examines the beginning of a string, and says: "I see no digit, but I can return a match, since the number of digits can be 0". It returns the empty string as a match, and goes on to b. And so on until the end of string.

    If you need to find all numbers, just use a + quantifier with \d shorthand class.

    See IDEONE demo

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