浅析Ruby中的正则表达式的使用
如果只是需要中查找字符串的text,不要使用正则表达式:string['text']
针对简单的结构,你可以直接使用string[/RE/]的方式来查询.
match=string[/regexp/]#getcontentofmatchedregexp first_group=string[/text(grp)/,1]#getcontentofcapturedgroup string[/text(grp)/,1]='replace'#string=>'textreplace'
当你不需要替结果分组时,使用非分组的群组。
/(first|second)/#bad /(?:first|second)/#good
不要使用Perl遗风的变量来表示匹配的正则分组(如$1,$2等),使用Regexp.last_match[n]作为替代。
/(regexp)/=~string ... #bad process$1 #good processRegexp.last_match[1]
避免使用数字化命名分组很难明白他们代表的意思。命名群组来替代。
#bad /(regexp)/=~string ... processRegexp.last_match[1] #good /(?<meaningful_var>regexp)/=~string ... processmeaningful_var
字符类有以下几个特殊关键字值得注意:^,-,\,],所以,不要转义.或者[]中的括号。
注意,^和$,他们匹配行首和行尾,而不是一个字符串的结尾,如果你想匹配整个字符串,用\A和\Z。
string="someinjection\nusername" string[/^username$/]#matches string[/\Ausername\Z/]#don'tmatch
针对复杂的正则表达式,使用x修饰符。可提高可读性并可以加入有用的注释。只是要注意空白字符会被忽略。
regexp=%r{ start#sometext \s#whitespacechar (group)#firstgroup (?:alt1|alt2)#somealternation end }x
sub/gsub也支持哈希以及代码块形式语法,可用于复杂情形下的替换操作.