Menu

Problem with lookahead

Help
2020-01-29
2020-02-03
  • Stacey Barr

    Stacey Barr - 2020-01-29

    Does Python Script support lookahead? I’m trying to get this regex to work, but it keeps failing.

    editor.rereplace(r"(^F1 VA \d+ )(?=.*\1)", r"! \1")
    

    For more backstory (and an example dataset), here’s a link to a reddit post.
    https://www.reddit.com/r/regex/comments/eutmta/finding_duplicates_using_a_lookahead/

    Thanks in advance for any input! This is driving me crazy.

     
  • Stacey Barr

    Stacey Barr - 2020-01-29

    Found the solution. For future reference, Python Scrip wants to see the single line flag used in the search.
    editor.rereplace(r"(^F1 VA \d+ )(?=[\s\S]*\1)",r"! \1")

     
    • Sasumner

      Sasumner - 2020-01-30

      "single line flag"?
      "Pythonscript wants..." -> it's about what YOU want :-)

      I think I see what you are saying though.
      You could have left your original regex alone and just added (?s)to the front of it.

       

      Last edit: Sasumner 2020-01-30
      • Stacey Barr

        Stacey Barr - 2020-01-31

        I tried using your suggestion in a number of different ways, but didn't have any luck. Where in the line were you expecting it to go?

         
        • Sasumner

          Sasumner - 2020-02-01

          Right at the front, just like I said. I tried it with your data set and got the results you expected.

          editor.rereplace(r"(?s)(^F1 VA \d+ )(?=.*\1)", r"! \1")

          without the (?s) the . won't match end-of-line characters. With it, it will. That way you can still use the . and don't have to resort to the [\s\S] trick (although that works fine, too).

          Aside: When you use the .* pattern, you should always first consider using it as .*? so that it matches minimally.

           
          • Stacey Barr

            Stacey Barr - 2020-02-03

            Ah! I see what you meant now. I started learning Python and regex thanks to this add in. I like how elegent and streamlined that addition was, and it worked perfectly. Thanks for the input!

             

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.