简体   繁体   中英

Perl regex to match but only replace in blocks

This is such a stupid question to ask - but I'm drawing a blank: I have a test string:

Foo|||bar||something|whatever

I need to replace || with |EMPTY_STRING| for each instance.

I'm doing:

s/\Q||/|EMPTY_STRING|/g;

The problem is, that this converts it to:

Foo|EMPTY_STRING||bar|EMPTY_STRING|something|whatever

Notice the || in there. I must be missing something stupid. What is it?

You can use lookaround in your regex:

s='Foo|||bar||something|whatever'

perl -pe 's/(?<=\|)(?=\|)/EMPTY_STRING/g' <<< "$s"

Foo|EMPTY_STRING|EMPTY_STRING|bar|EMPTY_STRING|something|whatever

RegEx Detail:

  • (?<=\|) : Lookbehind to assert that we have | behind current position
  • (?=\|) : Lookahead to assert that we have | ahead of current position

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