user2624744
user2624744

Reputation: 773

Conditional Python regex and named group

I have a string:

/foo/bar

and the following regex:

/(?P<g1>.*)/(?P<g2>.*)$

The string is matched by the pattern and two groups are captured:

g1 = foo

g2 = bar

How can I force an optional match?

I need that "/bar" is captured to g1 = "bar" (but not /bar/) if there is no second group the could be matched?

(Testing it with regex101)

Thanks

Upvotes: 1

Views: 2124

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

You need a start of string anchor ^ to restrict the string to only have 2 slahses. And as Avinash Raj noted you need to make some parts of your regex optional.

^/(?P<g1>[^/\n]*)/?(?P<g2>[^/\n]*)?(?<!/)$

See demo

The \n is only necessary in multiline mode so that [^/] could not match a newline.

REGEX EXPLANATION:

  • ^/ - Start of string and literal /
  • (?P<g1>[^/\n]*) - The first capturing group that is obligatory (must match 1 time) that matches any character but / (or \n too if you keep it), 0 or more times
  • /? - 0 or 1 / character
  • (?P<g2>[^/\n]*)? - Optional second capture group matching 0 or more characters other than / and \n
  • (?<!/)$ - End of string that is preceded with a character other than /.

Upvotes: 2

Related Questions