Perl 程式設計/正則表示式
外觀
正則表示式是複雜搜尋文字的工具,被認為是 Perl 語言的最強大功能之一。正則表示式可以和想要搜尋的文字一樣簡單,也可以包含萬用字元、邏輯甚至子程式。
若要在 Perl 中使用正則表示式,使用=~運算子將包含文字的變數繫結到正則表示式
$Haystack =~ /needle/;
如果 "needle" 包含在內,則返回 1$HayStack,否則返回 0。
$Haystack =~ /needle/i; # The i means "case-insensitive"
$Haystack =~ /(needle|pin)/; # Either/or statements
$Haystack =~ /needle \d/; # "needle 0" to "needle 9"
正則表示式也可以用來修改字串。可以透過使用正則表示式格式搜尋並替換複雜模式s///
$msg = "perl is ok";
$msg =~ s/ok/awesome/; # search for the word "ok" and replace it with "awesome"
($msg現在是 "perl 太棒了")