简体   繁体   中英

Perl MultiLine Regex Statement

I'm having some trouble getting a multiline regex statement to work for me.

Basically, I'm trying to remove empty lines following a ) ->. Matching the multiline section has been a bit tricky. Here's what I have so far:

perl -00 -p -i -e 's/\) ->(?=[^\n]*\n\n)$/\) ->\n/m' $filename

Here's my input/output:

Input:
setUp = 
  config: (cb) ->

    randomFunction (cb)->

       cb?()

  nestedObject: 
    key: (cb) ->

      cb?()


Output:
setUp = 
  config: (cb) ->
    cb?()

  nestedObject: 
    key: (cb) ->
      cb?()

Move the newline characters out of the look-ahead. Try

    s/\) ->(?=[^\n]*)\n\n/\) ->\n/mg;

Characters in the look-ahead are not replaced in a substitution.

(Actually, I don't see why you even need a look-ahead.

    s/\) ->.*\n\n/\) ->\n/mg;

also does the job, and any non-zero length sequence that matched the look-ahead would also make the whole pattern match fail.)

You also may want to use the /g flag, since you want to do this substitution more than once in the document.

Just do line by line processing with a flip-flop range, removing all blank lines as the end condition:

perl -i -pe '/\) ->\s*$/...!s/^\s*$//' file.txt

Perhaps a little easier to read:

perl -i -pe 'm{\) ->\s*$}...!s/^\s*$//' file.txt

You can use this replacement:

s/\) ->\R\K\R+//g

\\R is a shortcut for an atomic group that contains several common types of newlines
\\K removes all on the left from match result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM