preg_quote
preg_quote(string $str, ?string $delimiter = null): string
转义正则表达式中的特殊字符。
C C23
C23
#include <stdio.h>
#include <string.h>
int main(void) {
const char *special = ".\\+*?[^]$(){}=!<>|:-#"; // POSIX ERE 元字符集合
const char *s = "$3.50";
for (int i = 0; s[i]; i++) {
if (strchr(special, s[i])) putchar('\\'); // 元字符前补反斜杠
putchar(s[i]);
}
putchar('\n');
return 0;
}
输出
\$3\.50
C++ C++26
C++26
#include <iostream>
#include <string>
int main() {
const std::string special = ".\\+*?[^]$(){}=!<>|:-#"; // ERE 元字符集合
const std::string s = "$3.50";
for (char ch : s) {
if (special.find(ch) != std::string::npos) std::cout << '\\'; // 元字符前补反斜杠
std::cout << ch;
}
std::cout << "\n";
return 0;
}
输出
\$3\.50
C# v11.0.100
v11.0.100
// Regex.Escape 转义正则元字符(preg_quote 的对应物)
Console.WriteLine(System.Text.RegularExpressions.Regex.Escape("$3.50"));
输出
\$3\.50
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"regexp"
)
func main() {
fmt.Println(regexp.QuoteMeta("$3.50"))
}
输出
\$3\.50
Java v27.0.1
v27.0.1
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(Pattern.quote("$3.50"));
}
}
输出
\Q$3.50\E
JavaScript v26.13.1
v26.13.1
console.log("$3.50".replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
输出
\$3\.50
PHP v8.6.0
v8.6.0
echo preg_quote("$3.50", "/");
输出
\$3\.50
Python v3.15.2
v3.15.2
import re
print(re.escape("$3.50"))
输出
\$3\.50
Rust v1.99.1
v1.99.1
fn main() {
// regex crate 自带转义辅助函数(类似 preg_quote)
println!("{}", regex::escape("$3.50"));
}
输出
\$3\.50
TypeScript v26.13.1
v26.13.1
console.log("$3.50".replace(/[.*+?^${}()|[\]\\]/g, "\\$&")); // 手写转义:JS 无内置正则转义(RegExp.escape 为 ES2025 新增)
输出
\$3\.50
语言差异说明
C:标准库无现成转义函数,示例手写遍历元字符集合。
C++:标准库无现成转义函数,示例手写遍历元字符集合。
C#:Regex.Escape。
Go:regexp.QuoteMeta。
Java:语义不同——Pattern.quote 用 \Q...\E 包整段字面量而非逐字符转义。
JavaScript:无内置转义,惯用 .replace(/[.*+?^${}()|[\]\\]/g, "\\$&") 手写(ES2025 才引入 RegExp.escape)。
PHP:preg_quote 转义 PCRE 元字符,第二个参数指定分隔符时会一并转义分隔符(如 /)。
Python:re.escape(3.7+ 只转义特殊字符,但空格也会被转义)。
Rust:regex crate 的 regex::escape。
TypeScript:同 JS,手写转义正则。
安全场景:把用户输入裸拼进正则(如 '/' . $kw . '/')会让 .、*、(、[ 等元字符改写模式语义——轻则匹配错结果,重则灾难性回溯(ReDoS)拖垮服务;凡是动态拼模式,必须先过转义函数(preg_quote / re.escape / QuoteMeta / Regex.Escape / Pattern.quote / regex::escape),这是所有语言共通的安全底线。