preg_match_all

preg_match_all(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false

用正则表达式在字符串中查找全部匹配(不止第一处),返回匹配总数。

C C23

C23
#include <stdio.h>
#include <regex.h>

int main(void) {
    regex_t re;
    // POSIX ERE 没有 \w/\d 简写:用显式字符类
    regcomp(&re, "([a-z]+)=([0-9]+)", REG_EXTENDED);
    const char *s = "a=1 b=2 c=3";
    regmatch_t m[3];
    int count = 0;
    const char *p = s;
    while (regexec(&re, p, 3, m, 0) == 0) { // 循环:每次调用给出下一处匹配
        printf("%.*s: key=%.*s value=%.*s\n",
               (int)(m[0].rm_eo - m[0].rm_so), p + m[0].rm_so,
               (int)(m[1].rm_eo - m[1].rm_so), p + m[1].rm_so,
               (int)(m[2].rm_eo - m[2].rm_so), p + m[2].rm_so);
        count++;
        p += m[0].rm_eo; // 跳过当前匹配继续
    }
    printf("count: %d\n", count);
    regfree(&re);
    return 0;
}
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

C++ C++26

C++26
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string s = "a=1 b=2 c=3";
    std::regex re(R"(([a-z]+)=([0-9]+))"); // 原生字符串免去转义

    // sregex_iterator 遍历每一处匹配;尾迭代器终止循环
    auto end = std::sregex_iterator();
    int count = 0;
    for (auto it = std::sregex_iterator(s.begin(), s.end(), re); it != end; ++it) {
        std::cout << (*it)[0].str() << ": key=" << (*it)[1].str()
                  << " value=" << (*it)[2].str() << "\n";
        count++;
    }
    std::cout << "count: " << count << "\n";
    return 0;
}
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

C# v11.0.100

v11.0.100
using System.Text.RegularExpressions;

var text = "a=1 b=2 c=3";
var matches = Regex.Matches(text, @"([a-z]+)=([0-9]+)"); // 每处匹配的 MatchCollection

foreach (Match m in matches)
{
    Console.WriteLine($"{m.Value}: key={m.Groups[1].Value} value={m.Groups[2].Value}");
}
Console.WriteLine($"count: {matches.Count}");
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "regexp"
)

func main() {
    re := regexp.MustCompile(`([a-z]+)=([0-9]+)`) // Go 正则需先编译
    text := "a=1 b=2 c=3"

    // FindAllStringSubmatch:每处匹配给出 [全匹配, 组1, 组2];-1 表示全部匹配
    for _, m := range re.FindAllStringSubmatch(text, -1) {
        fmt.Printf("%s: key=%s value=%s\n", m[0], m[1], m[2])
    }
    fmt.Println("count:", len(re.FindAllStringSubmatch(text, -1)))
}
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

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) {
        Pattern pattern = Pattern.compile("([a-z]+)=([0-9]+)"); // 先编译
        Matcher matcher = pattern.matcher("a=1 b=2 c=3");

        int count = 0;
        while (matcher.find()) { // find() 逐处推进到所有匹配
            System.out.printf("%s: key=%s value=%s%n",
                    matcher.group(0), matcher.group(1), matcher.group(2));
            count++;
        }
        System.out.println("count: " + count);
    }
}
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

JavaScript v26.13.1

v26.13.1
const text = "a=1 b=2 c=3";
const re = /([a-z]+)=([0-9]+)/g; // 必须带 /g 标志:没有它 matchAll 直接抛错

// matchAll 逐个给出带捕获组的 match 对象
for (const m of text.matchAll(re)) {
  console.log(`${m[0]}: key=${m[1]} value=${m[2]}`);
}
console.log("count:", [...text.matchAll(re)].length);
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

PHP v8.6.0

v8.6.0
// 默认:$m[0] = 全部全匹配,$m[1]/$m[2] = 每个捕获组跨全部匹配的数组
preg_match_all('/([a-z]+)=([0-9]+)/', 'a=1 b=2 c=3', $m);
var_export($m);
echo "\n";
// PREG_SET_ORDER:每处匹配一个小数组 [全匹配, 组1, 组2]
preg_match_all('/([a-z]+)=([0-9]+)/', 'a=1 b=2 c=3', $m, PREG_SET_ORDER);
var_export($m);
echo "\n";
echo 'count: ', count($m), "\n";
输出
array (
  0 => 
  array (
    0 => 'a=1',
    1 => 'b=2',
    2 => 'c=3',
  ),
  1 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
  2 => 
  array (
    0 => '1',
    1 => '2',
    2 => '3',
  ),
)
array (
  0 => 
  array (
    0 => 'a=1',
    1 => 'a',
    2 => '1',
  ),
  1 => 
  array (
    0 => 'b=2',
    1 => 'b',
    2 => '2',
  ),
  2 => 
  array (
    0 => 'c=3',
    1 => 'c',
    2 => '3',
  ),
)
count: 3

Python v3.15.2

v3.15.2
import re

text = "a=1 b=2 c=3"
pattern = r"([a-z]+)=([0-9]+)"

# findall 直接返回捕获组元组的列表
print(re.findall(pattern, text))
# finditer 流式给出带 .group(n) 的 match 对象
for m in re.finditer(pattern, text):
    print(f"{m.group(0)}: key={m.group(1)} value={m.group(2)}")
print("count:", len(re.findall(pattern, text)))
输出
[('a', '1'), ('b', '2'), ('c', '3')]
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

Rust v1.99.1

v1.99.1
use regex::Regex; // regex crate

fn main() {
    let re = Regex::new(r"([a-z]+)=([0-9]+)").unwrap();
    let text = "a=1 b=2 c=3";

    // captures_iter 每处匹配流式给出一个 Captures
    let mut count = 0;
    for caps in re.captures_iter(text) {
        println!("{}: key={} value={}", &caps[0], &caps[1], &caps[2]);
        count += 1;
    }
    println!("count: {}", count);
}
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

TypeScript v26.13.1

v26.13.1
const text: string = "a=1 b=2 c=3";
const re: RegExp = /([a-z]+)=([0-9]+)/g; // matchAll 必须带 /g 标志

for (const m of text.matchAll(re)) {
  console.log(`${m[0]}: key=${m[1]} value=${m[2]}`);
}
console.log("count:", [...text.matchAll(re)].length);
输出
a=1: key=a value=1
b=2: key=b value=2
c=3: key=c value=3
count: 3

语言差异说明

C:POSIX <regex.h> 无「全匹配」一步到位 API,用 while + regexec 循环手动推进;ERE 无 \w/\d 简写,改用显式字符类。

C++:std::sregex_iterator 遍历所有匹配,范围 for 配 std::sregex_token_iterator 亦可。

C#:Regex.Matches 返回 MatchCollection(惰性求值),Count 即匹配总数。

Go:FindAllStringSubmatch(s, -1) 的第二参 -1 表示全部匹配(给 n 则只取前 n 处)。

Java:find() 循环逐处推进;无「一次拿全部」的数组 API。

JavaScript:matchAll(ES2020)返回迭代器,正则必须带 /g 标志否则抛 TypeError;老代码常用 match + /g(但只返回全匹配、无捕获组)。

PHP:与 preg_match 只找第一处不同,preg_match_all 找出全部并返回总数;$matches 默认按捕获组分组($m[0]=全匹配数组、$m[1]=第一组数组),PREG_SET_ORDER 翻转为按匹配分组(每处一个小数组)——后者适合逐条处理。

Python:re.findall 直接给组元组列表(简单场景够用),re.finditer 流式给 match 对象(要位置/惰性时用)。

Rust:regex crate 的 captures_iter 流式遍历,find_iter 只取全匹配。

TypeScript:同 JS,matchAll 需 /g 标志。