如何使用正则表达式将字符串拆分成组

3

我正在尝试使用以下正则表达式将字符串'A123456789123B'拆分为六个组:

'/^([A-Z]{1})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{3})([A-Z]{1})$/'

我尝试使用:

preg_split('/^([A-Z]{1})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{3})([A-Z]{1})$/', 'A123456789123B');

然而,它并不起作用。
我需要将字符串拆分成类似于这样的东西:
['A', '123', '456', '789', '123', 'B']

每个块中的字符数量固定吗? - user4035
本来会想到使用 preg_split 和 reset:(?:^.|...)\K,但有趣的是,这在不同版本的 PHP 中会产生不同的结果 - bobble bubble
3个回答

6

这种情况最好使用preg_match()函数:

preg_match('/^([A-Z]{1})(\d{3})(\d{3})(\d{3})(\d{3})([A-Z]{1})$/', 'A123456789123B', $matches);
array_shift($matches);

您的匹配数组将存储在$matches中。 $matches的第一个元素将包含整个匹配的字符串,其余元素将是括号中特定的捕获组。 我们使用array_shift()来删除第一个元素。

以下是一个示例:

php > var_dump(preg_match('/^([A-Z]{1})(\d{3})(\d{3})(\d{3})(\d{3})([A-Z]{1})$/', 'A123456789123B', $matches));
int(1)
php > var_dump($matches);
array(7) {
  [0]=>
  string(14) "A123456789123B"
  [1]=>
  string(1) "A"
  [2]=>
  string(3) "123"
  [3]=>
  string(3) "456"
  [4]=>
  string(3) "789"
  [5]=>
  string(3) "123"
  [6]=>
  string(1) "B"
}
php > array_shift($matches);
php > var_dump($matches);
array(6) {
  [0]=>
  string(1) "A"
  [1]=>
  string(3) "123"
  [2]=>
  string(3) "456"
  [3]=>
  string(3) "789"
  [4]=>
  string(3) "123"
  [5]=>
  string(1) "B"
}
php >

4

我认为你应该使用preg_match而不是split,因为split会搜索分隔符,而在这里你没有分隔符:

$str = 'A123456789123B';
preg_match('/^([A-Z]{1})([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{3})([A-Z]{1})$/', $str, $matches);
var_dump($matches);

那么你需要删除 $matches 的第一个键:

if ($matches) {
    array_shift($matches)
}

0

preg_split()非常适合直接提供所需的结果。

匹配字符串中的第一个字符或三个连续字符,使用\K释放匹配的字符,以便在分割时不会丢失任何字符。

代码:(演示)

$str = "A123456789123B";

var_export(
    preg_split('/(?:^.|...)\K/', $str)
);

输出:

array (
  0 => 'A',
  1 => '123',
  2 => '456',
  3 => '789',
  4 => '123',
  5 => 'B',
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接