RegEx: Look-behind to avoid odd number of consecutive backslashes

空扰寡人 提交于 2019-11-29 03:58:20
Etienne Perot

Last time I checked, PHP did not support variable-length lookbehinds. That is why you cannot use the trivial solution (?<![^\\](?:\\\\)*\\).

The simplest workaround would be to simply match the entire thing, not just the brackets part:

(?<!\\)((?:\\\\)*)\[(?<inside_brackets>.*?)]

The difference is that now, if you're using that regex in a preg_replace, you gotta remember to prefix the replacement string by $1, to restore the backslashes being there.

You could do it without any look-behinds at all (the (\\\\|[^\\]) alternation eats anything but a single back-slash):

^(\\\\|[^\\])*\[(?<brackets>.*?)\] 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!