跳轉到內容

Perl 程式設計/正則表示式運算子

來自華夏公益教科書,開放的書籍,面向開放的世界
前一頁:正則表示式 索引 下一頁:正則表示式參考

匹配字串

[編輯 | 編輯原始碼]
 # Shorthand form uses // to quote the regular expression
 $Text =~ /search words/;

 # The m function allows you to use your choice of quote marks
 $Text =~ m|search words|;
 $Text =~ m{search words};
 $Text =~ m<search words>;
 $Text =~ m#search words#;

將字串拆分為多個部分

[編輯 | 編輯原始碼]
 # The split function allows you to split a string wherever a regular expression is matched
 @ArrayOfParts = split( /,/, $Text);     # Splits wherever a comma is found
 @ArrayOfParts = split( /\s+/, $Text);   # Splits where whitespace is found
 @ArrayOfParts = split( /,\s*/, $Text);  # Comma followed by optional whitespace
 @ArrayOfParts = split( /\n/, $Text);    # Newline marks where to split

搜尋和替換字串

[編輯 | 編輯原始碼]
 # The s function allows you to search and replace within a string. s(ubstitute)
 $Text =~ s/search for/replace with/;
 $Text =~ s|search for|replace with|;
 $Text =~ s{search for}{replace with};

 # Putting a g (global) at the end, means it replaces all occurances and not just the first
 $Text =~ s/search for/replace with/g;

 # As with everything, putting an i (insensitive) at the end ignores the differences between
 # uppercase and lowercase.
 Use Locale;
 $Text =~ s/search for/replace with/i;

從字串中提取值

[編輯 | 編輯原始碼]
 # This function sets the variables $1, $2, $3 ... 
 #   to the information that it has extracted from a string.
 
 $Text =~ m/before(.*)after/;
 # So, if $Text was "beforeHelloafter", $1 is now "Hello"
   
 $Text =~ m/bef(.*)bet(.*)aft/;
 # This time, if $Text was "befOnebetTwoaft", $1 is now "One" and $2 is "Two"

 # It can also be used to extract certain kind of information.
 $Text =~ m|([^=]*)=(\d*)|;
   
 #If $Text was "id=889", $1 now equals "id" and $2 equals 889.
前一頁:正則表示式 索引 下一頁:正則表示式參考
華夏公益教科書