如何在模式中使用变量?
我想要这个:
my $project="SDK" //or something that i will get it after calling some function.
my $JIRA_regex = '(^| )($project)-(\d+)';
print "pattern = $JIRA_regex\n";
输出不好:
(^| )($project)-(\d+)
谢谢:)
1 - 是的我想使用$ project,作为匹配的字符串值或正则表达式:
2 - $ JIRA_regex将在代码上进一步匹配。
这是我现在正常运行的代码:
my $repo=$ARGV[0];
my $comment=$ARGV[1];
my $project_pattern="[A-Z]{2,5}";
if ($repo =~ "test1.git" or $repo =~ "test2.git")
{
$project_pattern = "\QSDK\E";
}
my $JIRA_regex = "(^| )($project_pattern)-(\\d+)";
if ( $comment =~ /$JIRA_regex/m )
{
print "matched $2-$3\n";
}
else
{
print "not matched\n";
}
答案 0 :(得分:4)
单引号不要插入变量;双引号。
my $project = "SDK"; # or whatever
my $JIRA_regex = "(^| )($project)-(\\d+)";
print "pattern = $JIRA_regex\n";
(请注意,我必须使用反斜杠转义才能将字符\d
放入字符串中。)
还有其他一些事情需要考虑:
$project
应该被解释为正则表达式吗? (可能不会,在这种情况下,它应该包含在\Q
\E
或quotemeta()
中。)$JIRA_regex
必须是纯字符串吗?如果没有,那么将它变成正则表达式对象会更容易。在这种情况下,更好的解决方案是:
my $project = "SDK"; # or whatever
my $JIRA_regex = qr/(^| )(\Q$project\E)-(\d+)/;
print "pattern = $JIRA_regex\n";