逃脱双背斜线

时间:2014-10-23 03:58:30

标签: php regex regex-negation

我需要匹配所有字符串,例如/(\:\w+)/(例如:hello),除非它在第一个字符上使用反斜杠进行转义,例如:\:hello。所以,在这种情况下,将不匹配。但是,如果我双重逃避,我可以忽略句子的反斜杠,并且会正常工作,例如:\\:hello只会收到:hello。等等。

实施例

  • test :hello test将匹配:hello
  • test \:hello test将不匹配
  • test \\:hello test将匹配:hello
  • test \\\:hello test将不匹配
  • test \\\\:hello test将匹配:hello
  • test \\\\\:hello test将不匹配
  • test \\\\\\:hello test将匹配:hello

4 个答案:

答案 0 :(得分:3)

您可以尝试使用\K丢弃之前匹配的字符)的以下正则表达式。

(?:\s|^)(?:\\\\)*\K:\w+

DEMO

答案 1 :(得分:1)

你走了:

$regex = '/(?<=^|[^\\\\])(?:[\\\\]{2})*(?P<tag>:\w+)/';

还有一些测试:

$tests = array(
    'test :hello test',
    'test \\:hello test',
    'test \\\\:hello test',
    'test \\\\\\:hello test',
    'test \\\\\\\\:hello test',
    'test \\\\\\\\\\:hello test',
    'test \\\\\\\\\\\\:hello test',
);
echo '<pre>';
foreach ($tests as $test) {
    preg_match($regex, $test, $match);
    if (empty($match)) {
        echo 'NOPE:  ', $test, "\n";
    } else {
        echo 'MATCH: ', $test, ' - ', $match['tag'], "\n";
    }
}

它给了我:

MATCH: test :hello test - :hello
NOPE:  test \:hello test
MATCH: test \\:hello test - :hello
NOPE:  test \\\:hello test
MATCH: test \\\\:hello test - :hello
NOPE:  test \\\\\:hello test
MATCH: test \\\\\\:hello test - :hello

答案 2 :(得分:0)

怎么样?

如果发生在行的开头

^(?:\\\\)*(:hello)

其他任何地方

\s(?:\\\\)*(:hello)\b

后方引用\1将包含:hello

参见示例

http://regex101.com/r/hF1mW6/1

答案 3 :(得分:0)

您是否尝试this: -

(?!<=)(:hello)
相关问题