2

我有一个存储设备名称的变量 say $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正则表达式的一部分与变量中的原始值匹配。

4

3 回答 3

3

单引号不插入。您可以使用双引号,但这需要大量转义。qr//正是为此目的而设计的。

qr/Dev:(\d)...Name:\Q$device_to_connect\E/
于 2012-04-19T05:25:37.510 回答
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";
}
于 2012-04-19T04:03:50.733 回答
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»
-->

调用组号只是调用/包含模式中前一个组的方式。希望这一点。请访问此处以供参考。

于 2012-04-19T04:06:34.743 回答