What does ?= mean in a regular expression?

前端 未结 4 1349
一向
一向 2020-11-29 20:21

May I know what ?= means in a regular expression? For example, what is its significance in this expression:

(?=.*\\d).
相关标签:
4条回答
  • 2020-11-29 20:55

    If you want to mask a credit card number (execpt) the last 4 digits/characters, you could use ?= in your regex.

    cc = "1234-5678"
    cc.replace(/.(?=....)/g, '#');
    

    cc = #####5678

    0 讨论(0)
  • 2020-11-29 21:03

    ?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured.

    Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

    0 讨论(0)
  • 2020-11-29 21:05

    The below expression will find the last number set in a filename before its extension (excluding dot (.)).

    '\d+(?=\.\w+$)'
    

    file4.txt will match 4.

    file123.txt will match 123.

    demo.3.js will match 3 and so on.

    0 讨论(0)
  • 2020-11-29 21:08

    (?=pattern) is a zero-width positive lookahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.

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