重复序列的正则表达式量词

时间:2017-03-22 09:03:26

标签: php regex

这是$ input:

The random 3x3 matrix is: 
0.5673 -0.3193 0.7516 
0.4423 0.6708 -0.6121 
-0.9798 0.0217 -0.1712 
Row 2 has the minimum sum of -1.1293

我想得到9个元素,行号和最小总和 这是模式:

$pattern = '/[^\A]+(-?[01]\.\d{4})[^\Z]+Row (\d) has the minimum sum of (-?\d+\.\d{4})\Z/'

但我发现它无法返回9个元素,例如:

preg_match_all($ pattern,$ input,$ matches)

的var_dump($匹配)

array(4) {
  [0]=>
  array(1) {
    [0]=>
    string(141) "The random 3x3 matrix is:<br>0.5673 -0.3193 0.7516<br>0.4423 0.6708 -0.6121<br>-0.9798 0.0217 -0.1712<br>Row 2 has the minimum sum of -1.1293"
  }
  [1]=>
  array(1) {
    [0]=>
    string(6) "0.1712"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [3]=>
  array(1) {
    [0]=>
    string(7) "-1.1293"
  }
}

如何修复$ pattern以分别获得9个元素。

1 个答案:

答案 0 :(得分:1)

您可以使用preg_match_all中的替换使用此正则表达式:

/(?:Row (\d+) has the minimum sum of )?(-?\d+\.\d+)/

RegEx Demo

请注意,非捕获组(?:...)是可选的,允许我们匹配上线的数字。

相关问题