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

Regex : how to optional capture a group

I’m trying to make an substring optional.
Here is the source :

Movie TOTO S09 E22 2022 Copyright

I want to optionally capture the substring : S09 E22

What I have tried so far :

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

/(Movie)(.*)(S\d\d\s*E\d\d)?/gmi

The problem is that it ends up by matching S09 E22 2022 Copyright instead of just S09 E22 :

Match 1 : 0-33  Movie TOTO S09 E22 2022 Copyright 
Group 1 : 0-5   Movie
Group 2:  5-33   TOTO S09 E22 2022 Copyright

Is there anyway to fix this issue ?

Regards

>Solution :

There are several errors in your regex:

  • Blank space after Movie is not considered.
  • (.*) matches everything after Movie.

Try online at https://regex101.com/

(Movie\s*)(\w*\s*)(S\d{2}\s*E\d{2}\s*)?((?:\w*\s*)*)
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