2013-02-28 78 views
-1

我需要確定搜索模式在字符串

是否

+審查CR @someuser存在的字符串。我怎樣才能做到這一點?

+0

您是否在尋找字串'@ someuser'或者是你試着g在「@」後面捕獲用戶名? – friedo 2013-02-28 22:55:21

+0

在什麼情況下? – squiguy 2013-02-28 22:58:17

回答

2

您將需要轉義元字符並使用匹配的正則表達式m//

if ($string =~ /\+review CR \@someuser/) { 
    # do something 
} 

請注意,您不能使用\Q ... \E轉義序列逃脫元字符,因爲@someuser仍將插值。你可以將它用於+,但是你仍然需要跳過@,所以這種方法更簡單。您也可以使用quotemeta功能。然而,在這種情況下,這可能是矯枉過正。

瞭解更多關於這perldoc perlop

1

使用index

$search_string = "+review CR \@someuser";
if (index($string, $search_string) != -1) { # found }

或者,如果您使用正則表達式,你要確保 '+' 和 '@' 是正確轉義:

if ($string =~ m#\+review CR \@someuser#) { # found }

+0

'字符串中的@someuser可能無意間插入? – TLP 2013-03-01 00:10:44

+0

逃跑並未正確完成。編輯。或者,可以用單引號聲明'$ search_string'。 – 2013-03-01 00:14:40