简体   繁体   中英

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:

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

Ignore the closing bracket denying it in your group capture

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM