Question marks in regular expressions

后端 未结 5 1020
难免孤独
难免孤独 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 02:46

    Some Other Uses of Question marks in regular expressions

    Apart from what's explained in other answers, there are still 3 more uses of Question Marks in regular expressions.    

    1. Negative Lookahead

      Negative lookaheads are used if you want to match something not followed by something else. The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point. x(?!x2)

      example

      • Consider a word There
      • Now, by default, the RegEx e will find the third letter e in word There.

        There
          ^
        
      • However if you don't want the e which is immediately followed by r, then you can use RegEx e(?!r). Now the result would be:

        There
            ^
        
    2. Positive Lookahead

      Positive lookahead works just the same. q(?=u) matches a q that is immediately followed by a u, without making the u part of the match. The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign.

      example

      • Consider a word getting
      • Now, by default, the RegEx t will find the third letter t in word getting.

        getting
          ^
        
      • However if you want the t which is immediately followed by i, then you can use RegEx t(?=i). Now the result would be:

        getting
           ^
        
    3. Non-Capturing Groups

      Whenever you place a Regular Expression in parenthesis(), they create a numbered capturing group. It stores the part of the string matched by the part of the regular expression inside the parentheses.

      If you do not need the group to capture its match, you can optimize this regular expression into

      (?:Value)
      

    See also this and this.

提交回复
热议问题