In their excellent answer to this Stack Overflow question, regex guru Wiktor Stribiżew provided this regex:
(?:\G(?!^)|^\[bar])(?:\s*\R\w =|[^\w\r\n] )\K\w
Within this expression, they use:
^\[bar]
to match [bar]
at the beginning of a line.
As you can see, the opening square bracket is escaped, but the closing square bracket is not.
Is this fine to do, as the regex engine will know that it is not currently within a bracketed character class? Or is it preferred to escape the closing square bracket in addition to the opening one?
As Wiktor points out, the regex engine being used is the Boost regex engine which is used by Notepad and other projects.
CodePudding user response:
Generally, I expect the answer to be "no", not required. But why live dangerously? Best to be absolutely consistent with correctness/security features.
Remember: if you need to optimize for regex storage space, you should probably employ compression rather than skirting the edges of the current implementation you're using.
So
Is this fine to do, as the regex engine will know that it is not currently within a bracketed character class?
All implementations I'm aware of, yes.
Or is it preferred to escape the closing square bracket in addition to the opening one?
Resounding yes!