简体   繁体   中英

Regex: Match string not containing substring not at the start of a line

^(pause|unpause)\s+chef\s+(on\s+)?(\S+)\s+(.*)(--dryrun)?

I want:

pause chef on staging nodes AND test --dryrun

to match and have "nodes AND test" and "--dryrun" in two separate matching groups.

as it stands, I get "nodes AND test --dryrun" in one matching group.

I searched around and using negative lookaheads didn't seem to work for my purpose because I want anything not containing "--dryrun", but not at the beginning of the line.

Thanks!

The problem is that you made (--dryrun) optional by following it with ? . Since (.*) is before it, that will match the longest string consistent with the rest of the expression matching, and since --dryrun is optional, it gobbles that up.

Use a non-greedy quantifier to make it use a shorter match.

You also need to anchor at the end of the line. Otherwise, .* will match the empty string after staging , and the optional --dryrun won't match anything (since it's optional).

^(pause|unpause)\s+chef\s+(on\s+)?(\S+)\s+(.*?)(--dryrun)?

DEMO

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