我试图从一串RTTTL命令中捕获命令,如下所示:
2a4, 2e, 2d#, 2b4, 2a4, 2c, 2d, 2a#4, 2e., e, 1f4, 1a4, 1d#, 2e., d, 2c., b4, 1a4, 1p, 2a4, 2e, 2d#, 2b4, 2a4, 2c, 2d, 2a#4, 2e., e, 1f4, 1a4, 1d#, 2e., d, 2c., b4, 1a4
我正在使用的正则表达式是(\S+),|$
,全局和多行打开,正如我读到$
在多行模式打开时匹配EOL,但是这不会发生,因此我不能捕获结束该行的最后一个命令1a4
。所有其他命令都从该组中捕获。
我应该用什么正则表达式捕获最后一个命令?
答案 0 :(得分:0)
只需添加一个前瞻或非捕获组,如下所示。并从组索引1中获取所需的字符串。
(\S+)(?:,|$)
OR
(\S+)(?=,|$)
使用前瞻时,您也不需要拥有捕获组。
\S+(?=,|$)
(?=,|$)
正向前瞻声明匹配必须后跟,
或行锚点的结尾。 \S+
匹配一个或多个非空格字符。
答案 1 :(得分:0)
另一种解决方案
$a = " 2a4, 2e, 2d#, 2b4, 2a4, 2c, 2d, 2a#4, 2e., e, 1f4, 1a4, 1d#, 2e., d, 2c., b4, 1a4, 1p, 2a4, 2e, 2d#, 2b4, 2a4, 2c, 2d, 2a#4, 2e., e, 1f4, 1a4, 1d#, 2e., d, 2c., b4, 1a4";
$r=explode(",",preg_replace("/\\s+/","",$a));
var_dump($r);
<强>输出:强>
array (size=37)
0 => string '2a4' (length=3)
1 => string '2e' (length=2)
2 => string '2d#' (length=3)
3 => string '2b4' (length=3)
4 => string '2a4' (length=3)
5 => string '2c' (length=2)
6 => string '2d' (length=2)
7 => string '2a#4' (length=4)
8 => string '2e.' (length=3)
9 => string 'e' (length=1)
10 => string '1f4' (length=3)
11 => string '1a4' (length=3)
12 => string '1d#' (length=3)
13 => string '2e.' (length=3)
14 => string 'd' (length=1)
15 => string '2c.' (length=3)
16 => string 'b4' (length=2)
17 => string '1a4' (length=3)
18 => string '1p' (length=2)
19 => string '2a4' (length=3)
20 => string '2e' (length=2)
21 => string '2d#' (length=3)
22 => string '2b4' (length=3)
23 => string '2a4' (length=3)
24 => string '2c' (length=2)
25 => string '2d' (length=2)
26 => string '2a#4' (length=4)
27 => string '2e.' (length=3)
28 => string 'e' (length=1)
29 => string '1f4' (length=3)
30 => string '1a4' (length=3)
31 => string '1d#' (length=3)
32 => string '2e.' (length=3)
33 => string 'd' (length=1)
34 => string '2c.' (length=3)
35 => string 'b4' (length=2)
36 => string '1a4' (length=3)