Question marks in regular expressions

后端 未结 5 1016
难免孤独
难免孤独 2020-12-08 02:30

I\'m reading the regular expressions reference and I\'m thinking about ? and ?? characters. Could you explain me with some examples their usefulness? I don\'t understand the

5条回答
  •  無奈伤痛
    2020-12-08 03:10

    Running the test harness from Oracle documentation with the reluctant quantifier of the "once or not at all" match X?? shows that it works as a guaranteed always-empty match.

    $ java RegexTestHarness
    
    Enter your regex: x?
    Enter input string to search: xx
    I found the text "x" starting at index 0 and ending at index 1.
    I found the text "x" starting at index 1 and ending at index 2.
    I found the text "" starting at index 2 and ending at index 2.
    
    Enter your regex: x??
    Enter input string to search: xx
    I found the text "" starting at index 0 and ending at index 0.
    I found the text "" starting at index 1 and ending at index 1.
    I found the text "" starting at index 2 and ending at index 2.
    

    https://docs.oracle.com/javase/tutorial/essential/regex/quant.html

    It seems identical to the empty matcher.

    Enter your regex:     
    Enter input string to search: xx
    I found the text "" starting at index 0 and ending at index 0.
    I found the text "" starting at index 1 and ending at index 1.
    I found the text "" starting at index 2 and ending at index 2.
    
    Enter your regex: 
    Enter input string to search: 
    I found the text "" starting at index 0 and ending at index 0.
    
    Enter your regex: x??
    Enter input string to search: 
    I found the text "" starting at index 0 and ending at index 0.
    

提交回复
热议问题