regex - 匹配奇数个转义符

标签 regex pcre backreference

我需要匹配 C++ 预处理器语句。现在,预处理器语句可以跨越多行:

#define foobar \
    "something glorious"

最后的反斜杠可能会被转义,因此以下结果会产生两行:
#define foobar \\
No longer in preprocessor.

问题是我如何有效地匹配显式连续行。我有以下我认为有效的表达。基本上,它测试反斜杠的数量是否为奇数。这样对吗?可以更有效地完成吗?
/
    [^\\]           # Something that's not an escape character, followed by …
    (?<escape>\\*?) # … any number of escapes, …
    (?P=escape)     # … twice (i.e. an even number).
    \\ \n           # Finally, a backslash and newline.
/x

(我正在使用 PHP,所以 PCRE 规则适用,但我很感激任何正则表达式白话的答案。)

最佳答案

我认为你让它变得比需要的更困难。尝试这个:

/
  (?<!\\)    # not preceded by a backslash
  (?:\\\\)*  # zero or more escaped backslashes
  \\ \n      # single backslash and linefeed
/x

关于regex - 匹配奇数个转义符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/816915/

相关文章:

php - 为什么带有 PCRE_UTF8 的 PHP preg_match_all 在 CLI 上和通过 Apache/mod_php 给出不同的结果?

regex - 在 sqlite3 中用 REGEXP 替换字符串的一部分

c++ - regex_match (""8 秒,regex (".{40000}"));?

javascript - 使用javascript检查字符串是否包含字符串中任何位置的url

php - 递归/子例程正则表达式以匹配 CSS 媒体查询

.htaccess - 模式中的 mod_rewrite RewriteRule 反向引用使用

PHP 正则表达式和相邻的捕获组

java - 模式匹配 : Matching a String with a pattern

regex - sed 4.2.2 中的数字匹配错误?

regex - Vim 正则表达式 : overwritten back references?