我有2个句子作为例子
Sentence 1 : "The word is [WORD1] , second word is [WORD2]"
Sentence 2 : "The word is [WORD1] , second word is [WORD2] , third word is [WORD3]"
我需要一个正则表达式,如果给出上述任何句子作为输入,它将提取方括号中的单词。
我尝试了以下一个
/^.+(\[[A-Z\d]+\]).+(\[[A-Z\d]+\]).*(\[[A-Z\d]+\])?$/)
我的第一句话输出正确为WORD1 WORD2 但是对于第二句,我得到输出WORD2 WORD3。
我需要做出哪些改变?
答案 0 :(得分:0)
答案 1 :(得分:0)
答案 2 :(得分:0)
使用g
修饰符启用global matching并将所有匹配项捕获到数组中:
my @array = $sentence =~ /(\[[A-Z\d]+\])/g;
答案 3 :(得分:0)
my $str = qq!The word is [WORD1] , second word is [WORD2] , third word is [WORD3]!;
while( $str =~ m/\[([^\]]+)\]/g ) {
print $1, "\n";
}
或者,如果您在数组中的内容:
my @words = $str =~ m/\[([^\]]+)\]/g;
答案 4 :(得分:0)
你的正则表达式有两个缺陷:
.*
,您可能会冒险进行比赛为了简化您的目标,我建议您在使用/g
modifier时匹配单词,而不是使用正则表达式匹配整行。此外,添加逻辑以检测何时未找到匹配项总是明智的。
use strict;
use warnings;
while (<DATA>) {
if (my @words = /\[(.*?)\]/g) {
print "Words = @words\n";
} else {
warn "No words found for line $.\n";
}
}
__DATA__
The word is [WORD1] , second word is [WORD2]
The word is [WORD1] , second word is [WORD2] , third word is [WORD3]
输出:
Words = WORD1 WORD2
Words = WORD1 WORD2 WORD3