Home > database >  Regex - optional character at the end of a string
Regex - optional character at the end of a string

Time:08-09

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:

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

CodePudding user response:

Ignore the closing bracket denying it in your group capture

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