Reputation: 342
I have a regex with multiple optional capture groups.
notify (?<action>[^\s]+)(?:(?<query>(?:(?! by ).)*))(?: by (?<id>\w+))?
The strings I am using to match are:
notify enable
notify disable
notify add hello
notify remove hello how are you
notify add 983734987 by id
notify remove hello by id
notify add hello by name
notify remove hello by name
As you can see, action
will either be enable
, disable
, add
, or remove
. query
SHOULD be either empty, hello
, hello how are you
or 983734987
but it always picks up a leading whitespace, id
will either be empty, id
or name
.
I can do more simple regex but when it looks like this I find it hard to understand. I have tried putting a ^\s
near query
so it doesn't have the leading whitespace but can't seem to get it to work.
So I need the query
capture group to ditch the leading whitespace it's picking up. Any help would be great.
Upvotes: 1
Views: 23
Reputation: 370809
I would put everything after action
into an optional group, and use lazy repetition for the query rather than (greedy repetition combined with negative lookahead), I think it's a bit more readable.
Careful of \s
because it can match newlines, which probably isn't desirable here. Rather than [^\s]+
, you can use \S+
. (\S
is the negation of \s
)
^notify (?<action>\S+)(?: +(?<query>.+?)(?: by (?<id>\w+))?)?$
https://regex101.com/r/xdM3I8/2
Upvotes: 1