2012-04-19 30 views
2

我有一個變量,用於存儲設備名稱,如$dev_to_connect = "XYZ keyboard"。我希望它將它包含在我的正則表達式中作爲模式匹配的一部分。我曾嘗試使用\Q..\E。但我發現它沒有幫助。如何在正則表達式中包含變量作爲使用perl的模式匹配的一部分

正則表達式我使用是'Dev:(\d)\r\n\tBdaddr:(..):(..):(..):(..):(..):(..)\r\n\tName:\Q$device_to_connect\E'

我想要的正則表達式的一部分\Q$device_to_connect\E與在變量初始值進行匹配。

+0

我需要使用組來獲取匹配列表。所以,我希望它可以包含在模式匹配中,而不需要對現有的正則表達式進行任何修改。 – chaitu 2012-04-19 03:59:40

回答

0

我認爲你有你的變量名混合在一起。你定義了$ dev_to_connect,但是你在你的regex中引用了$ 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"; 
} 
+0

我已經在我的表達式中試過這種正則表達式,並且它不起作用 – chaitu 2012-04-19 04:54:31

+0

它確實有效(請參閱編輯)。我建議你開始調試你的正則表達式。從儘可能簡單的正則表達式開始進行測試。 @ikegami是對的。你不能在單引號中使用你的變量。 – Markus 2012-04-19 06:49:26

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» 
--> 

調用的組號是唯一的呼叫/包括前一組中的圖案的方式。希望這個halp。請參閱here以供參考。

+0

你說的是搜索「單詞」。但這不是我的要求。我想要一個存儲在變量中的字符串作爲正則表達式的一部分進行匹配,我上面提到 – chaitu 2012-04-19 04:53:39

+0

我並不是說你想要什麼,而是向你展示一種實現你的目標的方式。這個例子顯示了在你的比賽中包含第一組的方法。 – Cylian 2012-04-19 05:19:09

3

單引號不插入。你可以使用雙引號,但這需要大量的轉義。 qr//是專爲此目的而設計的。

qr/Dev:(\d)...Name:\Q$device_to_connect\E/ 
相關問題