正则表达式仅匹配非转义字符串
一段时间以来,我一直在努力反对这个问题。仅当字符串未转义时,我才需要一个正则表达式来匹配该字符串。例如,此正则表达式需要匹配
和 \\
,但不匹配 \
,如下所示以及之前的任意数量的转义符(因此,匹配偶数个转义符,但不匹配奇数个)。
理想情况下,这并不重要,因为我正在寻找的这个美妙的小正则表达式花絮可以被任何人用来放在任何表达式前面,以仅返回正确的非转义字符串。该正则表达式必须在 PHP 中运行。
从理论上讲,这应该适用于前两个级别的转义,但事实并非如此:
(?<!\\(?<!\\\\))
此外,该方法必须非常大才能处理转义字符的所有可能长度。
更具体地说,我在 preg_replace() 中使用这个正则表达式。这样做是为了使 quake3 Arena 玩家别名脱色,使用正则表达式的另一个花絮来匹配着色字符串。基本上,我正在寻找一个匹配 ^
和 \\^
的正则表达式,但不匹配 \ ^<字母数字字符>
。
示例:
$find = "^3Foo^7bAR\^7kicks\\^bass";
$string = preg_replace('<regex>', '', $find);
应返回 $string = "Foobar\^7kicks\ass"
。
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"
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简短而简洁。
Short and concise.