preg_replace
preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null
用正则表达式替换字符串中的匹配。
C C23
C23
#include <regex.h>
#include <stdio.h>
#include <string.h>
int main(void) {
regex_t re;
regcomp(&re, "[0-9]+", REG_EXTENDED);
const char *s = "a1b22c333";
char out[64] = "";
const char *cur = s;
regmatch_t m[1];
while (regexec(&re, cur, 1, m, 0) == 0) { // 遍历每个匹配
strncat(out, cur, m[0].rm_so); // 匹配前的原文
strcat(out, "#");
cur += m[0].rm_eo; // 跳过上一次匹配
}
strcat(out, cur); // 剩余原文
printf("%s\n", out);
regfree(&re);
return 0;
}
输出
a#b#c#
C++ C++26
C++26
#include <iostream>
#include <regex>
#include <string>
int main() {
// std::regex_replace 默认替换全部匹配(等价于 /g)
std::cout << std::regex_replace(std::string("a1b22c333"),
std::regex(R"(\d+)"), "#")
<< "\n";
return 0;
}
输出
a#b#c#
C# v11.0.100
v11.0.100
Console.WriteLine(System.Text.RegularExpressions.Regex.Replace("a1b22c333", @"\d+", "#"));
输出
a#b#c#
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"regexp"
)
func main() {
fmt.Println(regexp.MustCompile(`\d+`).ReplaceAllString("a1b22c333", "#"))
}
输出
a#b#c#
Java v27.0.1
v27.0.1
public class Main {
public static void main(String[] args) {
System.out.println("a1b22c333".replaceAll("\\d+", "#"));
}
}
输出
a#b#c#
JavaScript v26.13.1
v26.13.1
console.log("a1b22c333".replace(/\d+/g, "#"))
输出
a#b#c#
PHP v8.6.0
v8.6.0
echo preg_replace('/\d+/', '#', "a1b22c333");
输出
a#b#c#
Python v3.15.2
v3.15.2
import re
print(re.sub(r"\d+", "#", "a1b22c333"))
输出
a#b#c#
Rust v1.99.1
v1.99.1
fn main() {
// replace_all 替换全部匹配(等价于 preg_replace 默认行为)
let re = regex::Regex::new(r"\d+").unwrap();
println!("{}", re.replace_all("a1b22c333", "#"));
}
输出
a#b#c#
TypeScript v26.13.1
v26.13.1
console.log("a1b22c333".replace(/\d+/g, "#"));
输出
a#b#c#
语言差异说明
C:无内置容器与高阶函数,示例以固定数组/缓冲与手写循环实现。
Go:默认替换全部。
Java:默认替换全部。
JavaScript:replace 需加 g 标志才替换全部匹配。
PHP:默认替换全部。
Python:默认替换全部。
Rust:用 regex crate 的 replace_all 替换全部匹配(默认行为即全局,等价 PHP preg_replace)。