Positive lookahead with javascript regex

后端 未结 2 704
花落未央
花落未央 2020-12-08 19:56

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         


        
相关标签:
2条回答
  • 2020-12-08 20:31

    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

    0 讨论(0)
  • 2020-12-08 20:48

    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

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