正则表达式首次匹配或操作

时间:2015-12-09 06:38:48

标签: regex perl

假设我们有以下字符串:

$text = "colors: red-FF0000,green-00FF00,blue-0000FF";

如果我想检查字符串是否包含red的十六进制值,我会使用以下语句:

($color,$hex) = $text =~ /colors\:\s+.*(red)-(.*?),.*/

我会为每个相应的变量获取值red00FF00。一切都很顺利。

现在,我想要检查字符串是否包含redgreen,但只获取第一个出现的颜色。我试过了

($color,$hex) = $text =~ /colors\:\s+.*(red|green)-(.*?),.*/

但我会green而不是$color获得red。有没有办法修复RegEx以获取管道列表中的第一个匹配颜色?我尝试使用(red|green)?,但似乎无效。

2 个答案:

答案 0 :(得分:1)

在空格匹配.*后删除\s+

my ($color,$hex) = $text =~ /colors\:\s+(red|green)-(.*?),.*/;

这是代码:

my $text = "colors: red-FF0000,green-00FF00,blue-0000FF";

my ($color,$hex) = $text =~ /colors\:\s+(red|green)-(.*?),.*/;

print "$color : $hex\n";

输出:

red : FF0000

答案 1 :(得分:1)

.*之前的

(red|green)是问题所在。它会进行贪婪匹配,吃掉red部分,然后在green找到匹配项。您需要在其后放置一个?来使其变得非贪婪。

($color,$hex) = $text =~ /colors\:\s+.*?(red|green)-(.*?),.*/

这样可行。