I have been messed up with regex.. I found it difficult for me..I have seen a code like:
function myFunction() {
var str = \"Is this all there is\";
va
The regex is(?= all)
matches the letters is
, but only if they are immediately followed by the letters all
Likewise, the regex is(?=there)
matches the letters is
, but only if they are immediately followed by the letters there
If you combined the two in is(?= all)(?=there)
, you are trying to match the letters is
, but only if they are immediately followed both by the letters all
AND the letters there
at the same time... which is not possible.
If you want to match the letters is
, but only if they are immediately followed either by the letters all
or the letters there
, then you can use:
is(?= all|there)
If, on the other hand, you want to match the letters is
, but only if they are immediately followed by the letters all there
, then you can just use:
is(?= all there)
What if I want is
to be followed by all
and there
, but anywhere in the string?
Then you can use something like is(?=.* all)(?=.*there)
The key to understanding lookahead
The key to lookarounds is to understand that the lookahead is an assertion that checks that something follows, or precedes at a specific position in the string. That is why I bolded immediately. The following article should dispel any confusion.
Reference
Mastering Lookahead and Lookbehind
The Positive Lookahead fails for the fact that there
does not immediately follow is.
is(?=there) # matches is when immediately followed by there
To match is if there
follows somewhere in the string, you would do:
is(?=.*there)
Explanation:
is # 'is'
(?= # look ahead to see if there is:
.* # any character except \n (0 or more times)
there # 'there'
) # end of look-ahead
See Demo
A detailed tutorial I recommend: How to use Lookaheads and Lookbehinds in your Regular Expressions