我想从字符串中提取一个值(不断变化)以便进一步处理.
字符串是
TPSM seed 4339CD65 pass 1 x 0 x 1 errors 0 pid 179947 rulefilecycle 0
TPSM seed 5339CD60 pass 1 x 9 x 2 errors 0 pid 179947 rulefilecycle 0
TPSM seed 2339CD61 pass 1 x 101 x 5 errors 0 pid 179947 rulefilecycle 0
TPSM seed 5339CD65 pass 1 x 19 x 6 errors 0 pid 179947 rulefilecycle 0
TPSM seed 9339CD65 pass 1 x 100 x 7 errors 0 pid 179947 rulefilecycle 0
Run Code Online (Sandbox Code Playgroud)
我希望在传递 1 xax n形式后提取值,其中我对'n'的值感兴趣.我正在尝试在perl中使用substr(),但由于数字不断变化,我无法编写像substr($ string,37,1)这样的东西.
如果没有某些正则表达式的substr(),我怎么能实现这个目的呢?
怎么样:
my ($n) = $string =~ /pass\s+\d+\s+x\s+\d+\s+x\s+(\d+)/;
Run Code Online (Sandbox Code Playgroud)
说明:
/ : Regex delimiter
pass : literally pass
\s+\d+\s+ : 1 or more spaces, 1 or more digits, 1 or more spaces (ie. the first number)
x : literally x
\s+\d+\s+ : 1 or more spaces, 1 or more digits, 1 or more spaces (ie. the second number)
x : literally x
\s+ : 1 or more spaces
(\d+) : 1 or more digits, captured in group 1 (ie. the third number)
/ : regex delimiter
Run Code Online (Sandbox Code Playgroud)
如果$string与正则表达式匹配,则在组1中捕获第三个数字,然后使用该组中的值填充变量$n.
如评论中所述,它可以简化为:
my ($n) = $string =~ /pass(?:\s+\d+\s+x){2}\s+(\d+)/;
Run Code Online (Sandbox Code Playgroud)
(?:...)非捕获组在哪里.