Extracting an optional project name in a fully optional pattern

34 Views Asked by At

I have this string "https://url/projects/x/flow/" and i want:

  1. if projects is existing in the string, capture x in a group named project_name
  2. if projects not existing in the string, then capture the whole string

The regex i am using is "\S*(projects\/(?<project_name>\w+))?"

But x is not captured and stored in a capturing group. Not sure what is wrong with my regex. Your help is appreciated

1

There are 1 best solutions below

0
Wiktor Stribiżew On

You can use

^(?:\S*?(projects\/(?<project_name>\w+)))?.*

See the regex demo.

Details:

  • ^ - start of string
  • (?:\S*?(projects\/(?<project_name>\w+)))? - an optional non-capturing group:
    • \S*? - any zero or more non-whitespace chars, as few as possible
    • (projects\/(?<project_name>\w+)) - Group 1: projects/ + one or more word chars after it captured into "project_name" group
  • .* - the rest of the string.