preg_replace
preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1, int &$count = null): string|array|null
Replaces matches in a string using a regular expression.
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) { // loop over each match
strncat(out, cur, m[0].rm_so); // original text before the match
strcat(out, "#");
cur += m[0].rm_eo; // skip past the previous match
}
strcat(out, cur); // remaining original text
printf("%s\n", out);
regfree(&re);
return 0;
}
Output
a#b#c#
C++ C++26
C++26
#include <iostream>
#include <regex>
#include <string>
int main() {
// std::regex_replace replaces all matches by default (equivalent to /g)
std::cout << std::regex_replace(std::string("a1b22c333"),
std::regex(R"(\d+)"), "#")
<< "\n";
return 0;
}
Output
a#b#c#
C# v11.0.100
v11.0.100
Console.WriteLine(System.Text.RegularExpressions.Regex.Replace("a1b22c333", @"\d+", "#"));
Output
a#b#c#
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"regexp"
)
func main() {
fmt.Println(regexp.MustCompile(`\d+`).ReplaceAllString("a1b22c333", "#"))
}
Output
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+", "#"));
}
}
Output
a#b#c#
JavaScript v26.13.1
v26.13.1
console.log("a1b22c333".replace(/\d+/g, "#"))
Output
a#b#c#
PHP v8.6.0
v8.6.0
echo preg_replace('/\d+/', '#', "a1b22c333");
Output
a#b#c#
Python v3.15.2
v3.15.2
import re
print(re.sub(r"\d+", "#", "a1b22c333"))
Output
a#b#c#
Rust v1.99.1
v1.99.1
fn main() {
// replace_all replaces every match (equivalent to preg_replace's default behavior)
let re = regex::Regex::new(r"\d+").unwrap();
println!("{}", re.replace_all("a1b22c333", "#"));
}
Output
a#b#c#
TypeScript v26.13.1
v26.13.1
console.log("a1b22c333".replace(/\d+/g, "#"));
Output
a#b#c#
Language differences
C: has no built-in containers or higher-order functions; the example uses fixed arrays/buffers and hand-written loops.
Go: replaces all matches by default.
Java: replaces all matches by default.
JavaScript: replace replaces all matches only with the g flag.
PHP: replaces all matches by default.
Python: replaces all matches by default.
Rust: uses regex::replace_all, which replaces all matches by default (same as PHP preg_replace).