Fabrizio Stellato
Fabrizio Stellato

Reputation: 1901

regex that matches an optional second group

Given the following:

1. foo
2. foo:asc
3. foo:desc
4. foo:
5. foo:burp

I would like to match a sequence of characters, and an optional second sequence only if prefixed by : and is asc or desc

I should match:

1. group 0 = foo, group 1 = <empty>
2. group 0 = foo, gorup 1 = asc
3. group 0 = foo, gorup 1 = desc
4. should fail
5. should fail

I've tried with:

  [^:]+:?(\basc\b|\bdesc\b)?

But it doesn't work as expected

Upvotes: 1

Views: 31

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You may use

^[^:]+(?::\b(asc|desc)\b)?$

See the regex demo

Details

  • ^ - start of string
  • [^:]+ - 1 or more chars other than :
  • (?::\b(asc|desc)\b)? - an optional occurrence of
    • : - a colon
    • \b(asc|desc)\b - an asc or desc as whole word
  • $ - end of string.

Upvotes: 2

Related Questions