68

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

(?=.*\d).
SilentGhost
  • 264,945
  • 58
  • 291
  • 279
theraneman
  • 699
  • 1
  • 5
  • 4

4 Answers4

96

?= 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).

cletus
  • 578,732
  • 155
  • 890
  • 933
  • 1
    Thanks cletus. Searching for information on this was not easy with a typical search engine :). – theraneman Oct 15 '09 at 08:54
  • 2
    This answer has been added to the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), under "Lookarounds". – aliteralmind Apr 10 '14 at 00:28
  • 1
    What do the words in the last parenthesis means, please? "but again that part is not captured". Does it mean that when I call a function, let's say, `match()`, it will match me certain string but the matched strings that will be returned does not include the characters "excluded" by `?=`? – scarface Jan 18 '19 at 09:22
  • 1
    @theraneman https://www.google.com/search?q=?= returns this questions as the second hit now :) – bers Mar 04 '19 at 12:42
12

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

Michael Foukarakis
  • 35,789
  • 5
  • 74
  • 113
3

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.

kisHoR
  • 910
  • 2
  • 9
  • 21
  • 5
    @TheLethalCoder An example makes it easier to understand. What's wrong with politely suggesting that this be added as a comment? – BobRodes Mar 11 '19 at 05:33
-2

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

PrestonDocks
  • 3,706
  • 8
  • 33
  • 59