跳转到内容

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.
前一页:正则表达式 索引 下一页:正则表达式参考
华夏公益教科书