gpt4 book ai didi

regex - 仅当模式存在时才匹配模式

转载 作者:行者123 更新时间:2023-12-01 23:18:14 26 4
gpt4 key购买 nike

我有以下代码:

#!/usr/bin/perl
use warnings;
use strict;

my $SourceStr='Foo - Name: Rob Time: 11/2/2011 13:47:30 State: Prelim 3 Optional: Some stuff here';
#my $SourceStr='Foo - Name: Rob Time: 11/2/2011 13:47:30 State: Prelim 3';

my $RegEx = qr/Name: (.+) Time: (.+) State: (.+) Optional: (.+?)( |$)/;

if ($SourceStr =~ m/$RegEx/) {
print "1=[$1]\n";
print "2=[$2]\n";
print "3=[$3]\n";
print "4=[$4]\n";
}

当使用第一个 $SourceStr 运行时,它按预期工作。但是,对于第二个被注释掉的,有没有办法让 $4 填充空字符串?

第一个字符串结果:

1=[Rob]
2=[11/2/2011 1:47:30 PM]
3=[3]
4=[Some stuff here]

第二个字符串结果:不匹配

想要:

1=[Rob]
2=[11/2/2011 1:47:30 PM]
3=[3]
4=[]

最佳答案

您可以使用更具体的正则表达式:

#!/usr/bin/perl
use warnings;
use strict;

my @SourceStrA=('Foo - Name: Rob Time: 11/2/2011 13:47:30 State: 3 Optional: Some stuff here',
'Foo - Name: Rob Time: 11/2/2011 13:47:30 State: 3');

my $RegEx = qr!Name:\s*(\w+)\s*Time:\s*([\d/]*\s*[\d:]*)\s*State:\s*(\d+)\s*(?:Optional:\s*(.*))?!;

for my $SourceStr (@SourceStrA) {
print "$SourceStr\n";
if ($SourceStr =~ m/$RegEx/) {
print "1=[$1]\n";
print "2=[$2]\n";
print "3=[$3]\n";
print "4=[$4]\n" if defined $4;
}
}

输出:

Foo - Name: Rob  Time: 11/2/2011 13:47:30  State: 3  Optional: Some stuff here
1=[Rob]
2=[11/2/2011 13:47:30]
3=[3]
4=[Some stuff here]
Foo - Name: Rob Time: 11/2/2011 13:47:30 State: 3
1=[Rob]
2=[11/2/2011 13:47:30]
3=[3]

关于regex - 仅当模式存在时才匹配模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14165648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com