我有一个变量,用于存储设备名称$dev_to_connect = "XYZ keyboard"
。我希望它作为模式匹配的一部分包含在我的正则表达式中。我尝试过使用\Q..\E
。但我发现它没有帮助。
我使用的正则表达式是'Dev:(\d)\r\n\tBdaddr:(..):(..):(..):(..):(..):(..)\r\n\tName:\Q$device_to_connect\E'
我希望正则表达式的\Q$device_to_connect\E
部分与变量中的原始值匹配。
答案 0 :(得分:3)
单引号不进行插值。你可以使用双引号,但这需要大量的转义。 qr//
是为此目的而设计的。
qr/Dev:(\d)...Name:\Q$device_to_connect\E/
答案 1 :(得分:0)
我认为你的变量名称混淆了。您定义$ dev_to_connect,但在正则表达式中引用$ device_to_connect。如果你在正则表达式中使用变量修复它很简单:
$var = 'foo';
if ($_ =~ /$var/) {
print "Got '$var'!\n";
}
以下是我的一个脚本的片段:
if ($ctlpt =~ /$owner/) {
($opt_i) && print "$prog: INFO: $psd is on $ctlpt.\n";
} else {
print "$prog: WARNING: $psd is on $ctlpt, and not on $owner.\n";
}
答案 2 :(得分:0)
假设你必须在文档中找到双字,这是如何做到的:
\b(\w+)\s+\1\b
这是解剖学:
<!--
\b(\w+)\s+\1\b
Options: ^ and $ match at line breaks
Assert position at a word boundary «\b»
Match the regular expression below and capture its match into backreference number 1 «(\w+)»
Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the same text as most recently matched by capturing group number 1 «\1»
Assert position at a word boundary «\b»
-->
调用组号只是在模式中调用/包含前一组的方法。希望这个停滞不前。访问here以供参考。