Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does the regular expression (?<!-) mean

Tags:

regex

php

pcre

I'm trying to understand a piece of code and came across this regular expression used in PHP's preg_replace function.

'/(?<!-)color[^{:]*:[^{#]*$/i'

This bit... (?<!-) doesnt appear in any of my reg-exp manuals. Anyone know what this means please? (Google doesnt return anything - I dont think symbols work in google.)

like image 920
spiderplant0 Avatar asked Jun 06 '12 21:06

spiderplant0


People also ask

What do regular expressions define?

Regular expressions are combinations of special character operators, which are symbols that control the search, that you can use to construct search strings for advanced find and/or replace searches.

What does \b mean in regex?

The \b metacharacter matches at the beginning or end of a word.


2 Answers

The ?<! at the start of a parenthetical group is a negative lookbehind. It asserts that the word color (strictly, the c in the engine) was not preceded by a - character.

So, for a more concrete example, it would match color in the strings:

color
+color
someTextColor

But it will fail on something like -color or background-color. Also note that the engine will not technically "match" whatever precedes the c, it simply asserts that it is not a hyphen. This can be an important distinction depending on the context (illustrated on Rubular with a trivial example; note that only the b in the last string is matched, not the preceding letter).

like image 103
eldarerathis Avatar answered Sep 24 '22 01:09

eldarerathis


PHP uses perl compatible regular expressions (PCRE) for the preg_* functions. From perldoc perlre:

"(?<!pattern)"
A zero-width negative look-behind assertion. For example
"/(?<!bar)foo/" matches any occurrence of "foo" that does
not follow "bar". Works only for fixed-width look-
behind.

like image 27
jordanm Avatar answered Sep 24 '22 01:09

jordanm