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.)
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.
The \b metacharacter matches at the beginning or end of a word.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With