How to delete a pattern when it is not found between two symbols in Perl?

后端 未结 1 760
庸人自扰
庸人自扰 2021-01-15 00:52

I have a document like this:

Once upon a time, there lived a cat.
The AAAAAA cat was ZZZZZZ very happy.
The AAAAAAcatZZZZZZ knew many other cats from many AA         


        
相关标签:
1条回答
  • 2021-01-15 01:40

    You have several possible ways:

    1. You can use the \K feature to remove the part you don't want from match result:

      s/AAAAAA.*?ZZZZZZ\K|cat//gs
      

      (\K removes all on the left from match result, but all characters on left are consumed by the regex engine. Consequence, when the first part of the alternation succeeds, you replace the empty string (immediatly after ZZZZZZ) with an empty string.)

    2. You can use a capturing group to inject as it (with a reference $1) the substring you want to preserve in the replacement string:

      s/(AAAAAA.*?ZZZZZZ)|cat/$1/gs
      
    3. You can use backtracking control verbs to skip and not retry the substring matched:

      s/AAAAAA.*?ZZZZZZ(*SKIP)(*FAIL)|cat//gs
      

      ((*SKIP) forces the regex engine to not retry the substring found on the left if the pattern fails later. (*FAIL) forces the pattern to fail.)

    Note: if AAAAAA and ZZZZZZ must be always on the same line, you can remove the /s modifier and process the data line by line.

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