浅析Ruby中的正则表达式的使用
(编辑:jimmy 日期: 2025/10/26 浏览:3 次 )
如果只是需要中查找字符串的 text, 不要使用正则表达式:string['text']
针对简单的结构, 你可以直接使用string[/RE/]的方式来查询.
match = string[/regexp/] # get content of matched regexp first_group = string[/text(grp)/, 1] # get content of captured group string[/text (grp)/, 1] = 'replace' # string => 'text replace'
当你不需要替结果分组时,使用非分组的群组。
/(first|second)/ # bad
/("htmlcode">
/(regexp)/ =~ string
...
# bad
process $1
# good
process Regexp.last_match[1]
避免使用数字化命名分组很难明白他们代表的意思。命名群组来替代。
# bad
/(regexp)/ =~ string
...
process Regexp.last_match[1]
# good
/("htmlcode">
string = "some injection\nusername"
string[/^username$/] # matches
string[/\Ausername\Z/] # don't match
针对复杂的正则表达式,使用 x 修饰符。可提高可读性并可以加入有用的注释。只是要注意空白字符会被忽略。
regexp = %r{
start # some text
\s # white space char
(group) # first group
(?:alt1|alt2) # some alternation
end
}x
sub/gsub 也支持哈希以及代码块形式语法, 可用于复杂情形下的替换操作.
下一篇:使用rbenv来管理Ruby版本的方法
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。