ChessSpider
ChessSpider

Reputation: 23

Match contents before and after an optional word in string

I have the following lines:

After=netfilter-persistent.service network-online.target docker.socket firewalld.service
After=network-online.target docker.socket firewalld.service netfilter-persistent.service
After=anothertest netfilter-persistent.service network-online.target docker.socket firewalld.service
After=network-online.target docker.socket firewalld.service

And I'm

  1. looking for a regex which captures the contents after After= and before and after netfilter-persistent.service, and
  2. everything after After= if netfilter-persistent.service is not present.

This regex does 1 but not 2:

^After=(.*?)?(?:netfilter-persistent\.service)(.*?)?$

This regex does 2 but not 1:

^After=(.*?)?(?:netfilter-persistent\.service)?(.*?)?$

This one comes close but then netfilter-persistent.service is still in Group 1:

^After=(.*?(?:netfilter-persistent\.service))?(.*?)?$

Upvotes: 2

Views: 77

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

You may make the first group non-capturing in your last pattern and wrap the .*? with a capturing group use

^After=(?:(.*?)netfilter-persistent\.service)?(.*)$

See the regex demo

Details

  • ^After= - After substring at the start of the string
  • (?:(.*?)netfilter-persistent\.service)? - an optional sequence of:
    • (.*?) - Group 1: any 0+ chars other than line break chars, as few as possible
    • netfilter-persistent\.service - a netfilter-persistent.service substring
  • (.*) - Group 2: any 0+ chars other than line break chars, as many as possible up to...
  • $ - the end of the string.

Upvotes: 2

Related Questions