David Rodrigues
David Rodrigues

Reputation: 12532

Escape double back-slash

I need to match all strings like /(\:\w+)/ (eg. :hello), except if it is escaped with back-slash on first character, like it: \:hello. So, in this case, will not match. But, if I double escape it, I can ignore the back-slash of sentence, and will work normally, like: \\:hello will receive :hello only. And so on.

Examples:

Upvotes: 1

Views: 118

Answers (4)

Avinash Raj
Avinash Raj

Reputation: 174696

You could try the below regex which uses \K (discards previously matched characters).

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

DEMO

Upvotes: 3

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

Here you go:

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

And some tests:

$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";
    }
}

It gives me:

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

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

What about

if occurs at the begining of the line

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

anywhere else

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

the back reference \1 will contain :hello

see the example

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

Upvotes: 0

Hussain Shabbir
Hussain Shabbir

Reputation: 14995

Did you try like this:-

(?!<=)(:hello)

Upvotes: 0

Related Questions