简体   繁体   中英

Regular Expression to match only nonescaped string

I've been bashing my head against this one for a while now. I have need of a regex to match a string only if it is not escaped. For example, this regex needs to match <string> and \\\\<string> , but not \\<string> , as well as any arbitrary number of escapes before it (so, match even number of escapes, but not odd number).

Ideally, it wouldn't matter as all what was, so that this wonderful little regex tidbit I'm looking for could be used by anyone to be slapped in front of any expression to only return properly non-escaped strings. This regex must function in PHP.

Theoretically, this should work for the first two levels of escape, but it doesn't:

(?<!\\(?<!\\\\))

And besides, that method would have to be extremely large to handle every possible length of escape characters.

More specifically, I'm using this regex in a preg_replace(). This is being done to decolorize quake3 Arena player aliases, using another tidbit of regex to match the colorization string. Basically, I'm looking for a regex that will match ^<alphanumeric-char> and \\\\^<alphanumeric-char> , but not \\^<alphanumeric-char> .

An example:

$find = "^3Foo^7bAR\^7kicks\\^bass";

$string = preg_replace('<regex>', '', $find);

Should return $string = "Foobar\\^7kicks\\ass" .

'~\\\\.(*SKIP)(*FAIL)|<string>~'

简洁明了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM