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 – optional character at the end of a string

I have a regex pattern almost working but I can’t seem to get it just right. I’m trying to capture the part of string after the first hyphen but that part can be inside of square brackets so I marked them as optional and it works for the opening bracket but the closing bracket matches if it’s present. So my question is, are optional characters at the end of a string matching differently than elsewhere? Any help is appreciated.

Here is the pattern I have now:

^start of string \- \[?(.*)\]?$

The example strings:

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

start of string - match - this part
start of string - [match - this part]

The results I’m getting:

match - this part
match - this part]

And the wanted result in both cases:

match - this part

>Solution :

Ignore the closing bracket denying it in your group capture

^start of string \\- \\[?(.*[^\\]])\\]?$
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