What does this do in regex (?= )

What does this do in regex (?= )

you can usually find answers to simple questions like this by Googling it like: “Javascript regex (?=)”

@yousef_040 See this leason

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead

In a regex, (?=) check patterns as a positive lookahead.

A complete list of special characters in regular expressions here.

1 Like

The thing i do not understand what lookahead means perhaps you could give an example.

Check out this link on MDN for (?=): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-lookahead

And for regular expression here on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Taylor(?=Swift) matches if name Taylor followed by Swift. That’s all.

It means that it will check if your string passes regex used after ?=, and will only do main regex if this one passes.
For example lets say we have string like this:
let str='My name is Babiboga and I am bad guy, I would like to blow up a bomb!';
We want to create regex that scans strings like this and returns names of people who use keywords like bomb. But we do not want regex to return actual word “bomb”, we want name of person. This is where we would use this lookahead. First we would check if string has word “bomb” in it with lookahead, then we will try to extract name, for example like this:

let str='My name is Babiboga and I am bad guy, I would like to blow up a bomb!';

let regex=/(?=.*bomb)(My name is \w+)/gi;

Here you can see 2 regex expressions, each is in its own () section.
But since first one, bomb, have “?” lookahead symbol, it means it will just say “yeah, my check is passing, go ahead and process this string, whoever comes next”. And then next expression will actually return match, because it is not just “looking” expression, but one that supposed to give you results. If first, lookahead, expression, would not find any bombs, second expression that looks for name would not be called, whole regex would be canceled.

1 Like

Lookahead will make sure the pattern matches without consuming characters.
So for example if you looking for a letter A, followed by the letter B A(?=B) the lookahead won’t consume the letter “B” and the match you will get back will only be “A”, but it will only match if B comes after the A.

So, typing A(?=B) for the string “BDAADBAB” will match the last part but only return the A.

Another example could be to match an address that end with .com without adding .com to the match.

.+(?=\.com)
Very simple example, will match any character one -> unlimited times. But won’t match until you write .com. Then it will consume all characters up to but not include the .com part.
abcdefg.com // abcdefg

1 Like

Important to note that it won’t consume Swift in the match, the match will only contain Taylor.

1 Like