preg_match
preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false
用正则表达式在字符串中查找匹配。
C C23
C23
#include <regex.h>
#include <stdio.h>
int main(void) {
regex_t re;
regcomp(&re, "[0-9]+", REG_EXTENDED); // POSIX 正则(非 C 标准库,POSIX 系统自带)
const char *s = "abc123def";
regmatch_t m[1];
if (regexec(&re, s, 1, m, 0) == 0) { // 匹配成功
printf("%.*s\n", (int)(m[0].rm_eo - m[0].rm_so), s + m[0].rm_so);
}
regfree(&re); // 释放正则对象
// 捕获组:pmatch[1..n] 保存组的偏移,等价 $m[1..n]
regex_t re2;
regcomp(&re2, "([0-9]+)-([0-9]+)-([0-9]+)", REG_EXTENDED);
regmatch_t g[4];
const char *date = "2026-11-19";
if (regexec(&re2, date, 4, g, 0) == 0) {
printf("year=%.*s month=%.*s day=%.*s\n",
(int)(g[1].rm_eo - g[1].rm_so), date + g[1].rm_so,
(int)(g[2].rm_eo - g[2].rm_so), date + g[2].rm_so,
(int)(g[3].rm_eo - g[3].rm_so), date + g[3].rm_so);
}
regfree(&re2);
return 0;
}
输出
123 year=2026 month=11 day=19
C++ C++26
C++26
#include <iostream>
#include <regex>
#include <string>
int main() {
std::smatch m; // 匹配结果
std::string s = "abc123def";
std::regex_search(s, m, std::regex(R"(\d+)")); // 原始字符串避免转义
std::cout << m[0] << "\n";
// 捕获组:m[1..n] 保存各组内容,等价 $m[1..n]
std::string date = "2026-11-19";
std::smatch d;
std::regex_search(date, d, std::regex(R"((\d+)-(\d+)-(\d+))"));
std::cout << "year=" << d[1] << " month=" << d[2] << " day=" << d[3] << "\n";
return 0;
}
输出
123 year=2026 month=11 day=19
C# v11.0.100
v11.0.100
var m = System.Text.RegularExpressions.Regex.Match("abc123def", @"\d+");
Console.WriteLine(m.Value);
// 捕获组:Groups[n] 取各组内容,等价 $m[1..n]
var dm = System.Text.RegularExpressions.Regex.Match("2026-11-19", @"(\d+)-(\d+)-(\d+)");
Console.WriteLine($"year={dm.Groups[1].Value} month={dm.Groups[2].Value} day={dm.Groups[3].Value}");
输出
123 year=2026 month=11 day=19
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\d+`)
fmt.Println(re.FindString("abc123def"))
// 捕获组:FindStringSubmatch 返回 [全匹配, 组1, 组2, ...]
dm := regexp.MustCompile(`(\d+)-(\d+)-(\d+)`).FindStringSubmatch("2026-11-19")
fmt.Printf("year=%s month=%s day=%s\n", dm[1], dm[2], dm[3])
}
输出
123 year=2026 month=11 day=19
Java v27.0.1
v27.0.1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Matcher m = Pattern.compile("\\d+").matcher("abc123def");
if (m.find()) {
System.out.println(m.group());
}
// 捕获组:group(n) 读取各组内容,等价 $m[1..n]
Matcher dm = Pattern.compile("(\\d+)-(\\d+)-(\\d+)").matcher("2026-11-19");
if (dm.find()) {
System.out.printf("year=%s month=%s day=%s%n", dm.group(1), dm.group(2), dm.group(3));
}
}
}
输出
123 year=2026 month=11 day=19
JavaScript v26.13.1
v26.13.1
const m = "abc123def".match(/\d+/);
console.log(m[0]);
// 捕获组:m[1..n] 保存各组内容,等价 $m[1..n]
const d = "2026-11-19".match(/(\d+)-(\d+)-(\d+)/);
console.log(`year=${d[1]} month=${d[2]} day=${d[3]}`)
输出
123 year=2026 month=11 day=19
PHP v8.6.0
v8.6.0
preg_match('/\d+/', "abc123def", $m);
echo $m[0], "\n";
// 捕获组写入 $m[1..n]:把日期拆解成各部分
preg_match('/(\d+)-(\d+)-(\d+)/', '2026-11-19', $d);
echo "year={$d[1]} month={$d[2]} day={$d[3]}";
输出
123 year=2026 month=11 day=19
Python v3.15.2
v3.15.2
import re
m = re.search(r"\d+", "abc123def")
print(m.group(0))
dm = re.search(r"(\d+)-(\d+)-(\d+)", "2026-11-19")
print(f"year={dm.group(1)} month={dm.group(2)} day={dm.group(3)}") # 捕获组
输出
123 year=2026 month=11 day=19
Rust v1.99.1
v1.99.1
fn main() {
// regex crate:Regex::new 编译模式(失败返回 Err),find 取第一个匹配
let re = regex::Regex::new(r"\d+").unwrap();
let m = re.find("abc123def").unwrap();
println!("{}", m.as_str()); // 等价于 preg_match 的 $m[0]
// 捕获组:captures() 可按下标取各组,等价 $m[1..n]
let caps = regex::Regex::new(r"(\d+)-(\d+)-(\d+)").unwrap()
.captures("2026-11-19").unwrap();
println!("year={} month={} day={}", &caps[1], &caps[2], &caps[3]);
}
输出
123 year=2026 month=11 day=19
TypeScript v26.13.1
v26.13.1
const m = "abc123def".match(/\d+/);
console.log(m![0]); // TS:match 可能返回 null,需要非空断言(此处必然匹配)
const d = "2026-11-19".match(/(\d+)-(\d+)-(\d+)/);
console.log(`year=${d![1]} month=${d![2]} day=${d![3]}`); // 捕获组
输出
123 year=2026 month=11 day=19
语言差异说明
C:使用 POSIX <regex.h>(非 ISO C 标准,但 POSIX 系统自带)。
C++:用 <regex>(ECMAScript 语法为默认),原生字符串 R"(...)" 免去转义。
C#:用 Regex.Match(System.Text.RegularExpressions),未命中返回空 Match。
Go:需先编译正则对象。
Java:需先编译正则对象。
JavaScript:match 返回数组。
PHP:preg_match 返回 0/1 并把捕获写入引用参数 $m。
Python:re.search 返回 match 对象用 .group()。
Rust:正则用 regex crate:Regex::new 编译正则,find 返回首个匹配(captures 可取捕获组,等价 PHP 的 $m)。