使用Perl在方括号"[]"之间提取数据

Nai*_*idu 4 regex perl

我正在使用正则表达式从弯曲括号(或"括号")中提取数据a,b,(a,b)如下所示从中提取.我有一个文件,其中每一行都会像

this is the range of values (a1,b1) and [b1|a1]
this is the range of values (a2,b2) and [b2|a2]
this is the range of values (a3,b3) and [b3|a3]
Run Code Online (Sandbox Code Playgroud)

我使用下面的字符串来提取a1,b1,a2,b2等...

@numbers = $_ =~ /\((.*),(.*)\)/
Run Code Online (Sandbox Code Playgroud)

但是,如果我想从方括号中提取数据[],我该怎么办?例如

this is the range of values (a1,b1) and [b1|a1]
this is the range of values (a1,b1) and [b2|a2]
Run Code Online (Sandbox Code Playgroud)

我需要提取/匹配方括号中的数据而不是曲线括号.

Mar*_*ulz 25

[更新]与此同时,我写了一篇关于具体问题的博客文章,.*我在下面描述:为什么在正则表达式中使用.*几乎不是你真正想要的


如果你的标识符a1,b1等等从不包含逗号或括号自己,你应该使用沿着下面的线条组成的图案,以避免回溯地狱:

/\[([^,\]]+),([^,\]]+)\]/
Run Code Online (Sandbox Code Playgroud)

这是Regex101的一个工作示例.

贪婪量词的问题.*是,你很可能在开始时消耗太多,以便正则表达式引擎必须进行大量的回溯.即使你使用非贪婪的量词,引擎也会做更多的匹配尝试,因为它一次只消耗一个字符,然后尝试提升模式中的位置.

(你甚至可以使用原子组来使匹配更加高效.)