4

I was using a regex for extracting data from curved brackets (or "parentheses") like extracting a,b from (a,b) as shown below. I have a file in which every line will be like

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]

I'm using the following string to extract a1,b1, a2,b2, etc...

@numbers = $_ =~ /\((.*),(.*)\)/

However, if I want to extract the data from square brackets [], how can I do it? For example

this is the range of values (a1,b1) and [b1|a1]
this is the range of values (a1,b1) and [b2|a2]

I need to extract/match only the data in square brackets and not the curved brackets.

4

5 回答 5

27

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


如果您的 identifiersa1b1本身从不包含逗号或方括号,您应该使用如下所示的模式以避免回溯地狱:

/\[([^,\]]+),([^,\]]+)\]/

这是 Regex101 上的一个工作示例

像贪心量词这样的问题.*是,您很可能在开始时消耗太多,因此正则表达式引擎必须进行大量回溯。即使您使用非贪婪量词,引擎也会进行比必要更多的匹配尝试,因为它一次只会消耗一个字符,然后尝试推进模式中的位置。

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

于 2014-06-02T09:35:59.490 回答
2
#!/usr/bin/perl
# your code goes here
my @numbers;
while(chomp(my $line=<DATA>)){
    if($line =~ m|\[(.*),(.*)\]|){
    push @numbers, ($1,$2);
    }
}
print @numbers; 
__DATA__
this is the range of values [a1,b1]
this is the range of values [a2,b2]
this is the range of values [a3,b3]

演示

于 2014-06-02T10:12:19.920 回答
1

您可以使用非贪婪量词匹配它*?

my @numbers = $_ =~ /\[(.*?),(.*?)\]/g;

或者

my @numbers = /\[(.*?),(.*?)\]/g;

简而言之。

更新

my @numbers = /\[(.*?)\|(.*?)\]/g;
于 2014-06-02T09:15:38.140 回答
0

我知道我在这里有点晚了,但没有一个答案正确回答了 OP 的问题,而真正与方括号一起匹配整个问题的答案[]。显然,OP想要匹配括号内的内容。

  • 匹配方括号内的所有内容以及括号。例子

    \[[^\[\]]*]

  • 要匹配方括号内的所有内容(不包括括号本身),请使用正向查找和向后查找。例子

    (?<=\[)[^\[\]]*(?=\])

于 2020-09-20T19:07:46.110 回答
0

使用下面的代码

$_ =~ /\[(.*?)\|(.*?)\]/g;

现在,如果模式匹配成功,提取的值将存储在$1and中$2

于 2020-04-24T09:03:00.293 回答