简体   繁体   中英

Find all special characters in a MySQL regexp

I want to match on this regular expression: \\[\\[\\.\\\\{0,}(.)?\\.\\]\\] , so:

a [ followed by a [ and a . , then a possible number of \\ (0 or more), then a single character and then . followed by two ] 's

This is to find [[.g.]] as g , '[[.\\g.]]' as g , but also [[.\\\\g.]] as g . I have the following code (for example):

preg_match_all( '/\[\[\.(.)?\.\]\]/', "[[.g.]]", $matches );

This finds g as the match. If I want to ignore escape characters I would change my pattern into \\[\\[\\.\\\\{0,}(.)?\\.\\]\\] , so:

preg_match_all( '/\[\[\.\\{0,}(.)?\.\]\]/', "[[.\\\\g.]]", $matches );

I would expect g back, but I'm getting nothing. The regexp now means: two [ , following by a . , any number of escape characters, then the character we want to find, followed by .]] . What am I doing wrong?

You're probably not able to match using your regex because two backslashes mean one (due to escaping), try this (with two but escaped slashes, so 4 in total):

$re = '/\[\[\.\\\\{0,}(.)?\.\]\]/m';
$str = '[[.g.]]
[[.\\g.]]
[[.\\\\g.]]
[[.\\\\\\\\g.]]';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

Live demo here

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