2013年2月25日 星期一

perl 匹配字串

http://www.cbi.pku.edu.cn/chinese/documents/perl/perl6.htm

http://blog.sina.com.cn/s/blog_50873f890100a13i.html
''  q//  字面字串
""  qq//  字面字串
``  qx//  命令執行
()  qw//  單字串列
//  m//  樣式比對
s///  s///  樣式代換
y///  tr///  字符轉譯
""  qr//  正規表示式

@test = qw/test perl is fun/;
use Data::Dumper;
print Dumper @test;
#$VAR1 = 'test';
#$VAR2 = 'perl';
#$VAR3 = 'is';
#$VAR4 = 'fun';
 
$reg = "test";
$test = "atesta";
$test =~ s/$reg/bear/;
print $test;  #abeara
 
`mkdir test2`;  #建立test2資料夾
qx/mkdir test3/;  #建立test2資料夾



替換操作符
选项 描述
g 改变模式中的所有匹配
i 忽略模式中的大小写(case insensitive)
e 替换字符串作为表达式
m 将待匹配串视为多行
o 仅赋值一次
s 将待匹配串视为单行
x 忽略模式中的空白


二、匹配操作符 =~、!~
    =~检验匹配是否成功:$result = $var =~ /abc/;若在该字符串中找到了该模式,则返回非零值,即true,不匹配则返回0,即false。!~则相反。

使用index去判斷匹配字串:
$filename = "bear_test-1234578";
print index($filename,"bear_test"); # 小於零時表示$filename與第二個參數("bear_test") 不匹配

搜尋中文: \p{Han}  (未測試 ) 無法使用
http://www.regular-expressions.info/unicode.html#prop
其他特殊表示式:
http://www.gnu.org/software/grep/manual/html_node/Character-Classes-and-Bracket-Expressions.html

perl正規式的escape sequence
http://www.regular-expressions.info/characters.html
Escaping a single metacharacter with a backslash works in all regular expression flavors. Many flavors also support the \Q…\E escape sequence. All the characters between the \Q and the \E are interpreted as literal characters. E.g. \Q*\d+*\E matches the literal text *\d+*. The \E may be omitted at the end of the regex, so \Q*\d+* is the same as \Q*\d+*\E. This syntax is supported by the JGsoft enginePerlPCREPHPDelphi, and Java, both inside and outside character classes. Java 4 and 5 have bugs that cause \Q…\E to misbehave, however, so you shouldn't use this syntax with Java.

=> 在perl正規式中\Q..\E中間的內容會被解釋為原文字符


沒有留言:

張貼留言