regex Perl正则表达式读取方括号

zbdgwd5y  于 2023-05-19  发布在  Perl
关注(0)|答案(2)|浏览(134)

我想在方括号内读位,也要方括号。棘手的部分是class4。sample1[1]不是位。只在行尾使用位。
示例:

File1.txt
class1->Signal = sample1_sample2.sample3_sample4[4:4];
class2->Signal = sample1.sample2.sample3_sample4_sample5[2];
class3->Signal = sample1+sample2_sample3.sample4.sample5sample7[7:3];
class4->Signal = sample1[1]+sample2_sample3.sample4.sample5sample7[7:3];

预期结果:

class1 bit = [1:2]
class2 bit = [2]
class3 bit = [7:3]
class4 bit = [7:3]

我使用正则表达式,但方括号无法读取。[] = Used for set of characters.... = Any character except newline.参考:https://www.geeksforgeeks.org/perl-regex-cheat-sheet/
我的代码:

my $file = "$File1.txt";
my $line;

open (FILE,"<", $file) or die "Cannot open a file: $!";
while (<FILE>){
    my $line = $_;
    if ($line =~ m/[..]/){
        $line = $&;
    }
}
close (FILE);

结果仅显示:.........
我希望你们能帮我出主意。谢谢。

jljoyd4f

jljoyd4f1#

使用所示的示例,请尝试在PCRE中执行以下正则表达式。

^([^-]*)->.*?(\[[^]]*\]);$

下面是上述正则表达式的online demo

***解释说明:***为上述正则表达式增加详细解释说明。

^            ##Matching from starting of the value here.
(            ##Creating 1st capturing group here.
  [^-]*      ##Matching everything before very next occurrence of - here.
)            ##Closing capturing group here.
->           ##Matching literal -> here.
.*?          ##Using lazy match to match till next occurrence of [ mentioned below.
(            ##Creating 2nd capturing group here.
  \[[^]]*    ##matching literal [ following by very first occurrence of ] here.
  \]         ##Matching literal ] here.
)            ##Closing 2nd capturing group here.
;$           ##Mentioning literal ; at the end of the value here.
nxowjjhe

nxowjjhe2#

您可以选择要删除的部分,并替换为bit =

^[^-]*\K->.*(?=\[[^][]*\];$)

说明

  • ^字符串开头
  • [^-]*\K匹配除-以外的可选字符,并忘记目前使用\K匹配的字符
  • ->.*匹配->和该行的其余部分
  • (?=\[[^][]*\];$)正向预测,在行的末尾置位[...];

查看regex demo和Perl演示
示例

use strict;
use warnings;

while (<DATA>)
{
  s/^[^-]*\K->.*(?=\[[^][]*\];$)/ bit = /;
  print $_;
}

__DATA__
class1->Signal = sample1_sample2.sample3_sample4[4:4];
class2->Signal = sample1.sample2.sample3_sample4_sample5[2];
class3->Signal = sample1+sample2_sample3.sample4.sample5sample7[7:3];
class4->Signal = sample1[1]+sample2_sample3.sample4.sample5sample7[7:3];

输出

class1 bit = [4:4];
class2 bit = [2];
class3 bit = [7:3];
class4 bit = [7:3];

或者更具体一点的正则表达式:

^class\d+\K->.*(?=\[[^][]*\];$)

另见regex demo

相关问题