Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Second optional capturing group depending on optional delimiter in regex

I’m sorry for asking this maybe duplicate question. I checked the existing questions and answers about optional capturing groups. I tried some things but I’m not able to translate the answer to my own example.

This are two imput lines

id:target][label
id:target

I would like to capture id: (group 1), target (group 2) and if ][ is present label (group 3).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The used regex (Python regex) only works on the first line (live example on regex101).

^(.+:)(.*)\]\[(.*)

enter image description here

In the other examples I don’t get what the regex makes a capturing group optional. And maybe the delimiter ][ used by me also mix up with my understanding problem.

One thing I tried was this

^(.+:)(.*)(\]\[(.*))?

This doesn’t work as expected
enter image description here

>Solution :

You could write the pattern using an anchor at the end, a negated character class for group 1, a non greedy quantifier for group 2 and then optionally match a 3rd part:

^([^:]+:)(.*?)(?:]\[(.*))?$

Explanation

  • ^ Start of string
  • ([^:]+:) Group 1, match 1+ chars other than : and then match : using a negated character class
  • (.*?) Group 2, match any char, as few as possible
  • (?: Non capture group to match as a whole part
    • ]\[ Match ][
    • (.*) Group 3, match any character
  • )? Close the non capture group and make it optional
  • $ End of string

See a regex101 demo

If you are only matching for example word characters, this you might consider:

^([^:]+:)(\w+)(?:]\[(\w+))?

See a another regex101 demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading