字符前未转义的反斜杠的正确正则表达式是什么? [英] What is the proper regular expression for an unescaped backslash before a character?

查看:53
本文介绍了字符前未转义的反斜杠的正确正则表达式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想表示 \q(或任何其他特定的反斜杠转义字符").也就是说,我想匹配 \q 而不是 \\q,因为后者是一个反斜杠转义的反斜杠,后跟一个 q.然而 \\\q 会匹配,因为它是一个反斜杠转义的反斜杠,后跟一个反斜杠转义的 q.(好吧,它会匹配末尾的 \q,而不是开头的 \\.)

Let's say I want to represent \q (or any other particular "backslash-escaped character"). That is, I want to match \q but not \\q, since the latter is a backslash-escaped backslash followed by a q. Yet \\\q would match, since it's a backslash-escaped backslash followed by a backslash-escaped q. (Well, it would match the \q at the end, not the \\ at the beginning.)

我知道我需要一个否定的回顾,但他们总是把我的头打成一个结,特别是因为反斜杠本身必须在正则表达式中转义.

I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.

推荐答案

更新:我新的和改进的 Perl 正则表达式,支持超过 3 个反斜杠:

Updated: My new and improved Perl regex, supporting more than 3 backslashes:

/(?<!\\)    # Not preceded by a single backslash
  (?>\\\\)* # an even number of backslashes
  \\q       # Followed by a \q
  /x;

或者如果您的正则表达式库不支持扩展语法.

or if your regex library doesn't support extended syntax.

/(?<!\\)(?>\\\\)*\\q/

我的测试程序的输出:

q does not match
\q does match
\\q does not match
\\\q does match
\\\\q does not match
\\\\\q does match

旧版本

/(?:(?<!\\)|(?<=\\\\))\\q/

这篇关于字符前未转义的反斜杠的正确正则表达式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆