[英]Perl Regex for Strings with special characters and double quotes
我一直在嘗試為可用的配置文件中的文本使用正則表達式,該文件具有以下內容
Employee Name="John"
Address="Sector-15"
我正在將整個配置數據作為變量 $employeeData 中的字符串讀取
我如何編寫一個正則表達式條件,如果在 $employeeData 值中找到文本Address="Section-15" ,我將增加一個計數器。
我知道為帶有字符和數字的字符串編寫簡單的正則表達式,但我正在努力為字符串編寫正則表達式以考慮雙引號和“-”字符,如 Address="Sector-15"
我正在以這種方式嘗試
if($employeeData =~ {regex}) #regex for Address="Sector-15"
{
increment a variable.
}
任何提供對這些條件的理解或答案的鏈接將不勝感激!
匹配Address="Section-15"
正則表達式可能是:
/.*/
(匹配任何東西,所以也應該匹配這個字符串)/^Address="Section-15"\\z/
(只匹配字符串)/.*=".*"/
(匹配任何后跟=
后跟雙引號中的內容) 正則表達式的語法不包含{}
:
if ($employee_data =~ /Address=".*"/) {
++$counter;
}
如果要將正則表達式存儲在變量中,請使用qr//
:
my $regex = qr/Address="(.*)"/;
while (my $employee_data = <$config>) {
++$counter if $employee_data =~ /$regex/;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.