Reputation: 12532
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:
test :hello test
will match :hello
test \:hello test
will not matchtest \\:hello test
will match :hello
test \\\:hello test
will not matchtest \\\\:hello test
will match :hello
test \\\\\:hello test
will not matchtest \\\\\\:hello test
will match :hello
Upvotes: 1
Views: 118
Reputation: 174696
You could try the below regex which uses \K
(discards previously matched characters).
(?:\s|^)(?:\\\\)*\K:\w+
Upvotes: 3
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
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