编程语言


浅析Ruby中的正则表达式的使用

网络编程 浅析Ruby中的正则表达式的使用 06-21


如果只是需要中查找字符串的 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
  /(?:first|second)/ # good

不要使用 Perl 遗风的变量来表示匹配的正则分组(如 $1,$2 等),使用 Regexp.last_match[n] 作为替代。

  /(regexp)/ =~ string
  ...

  # bad
  process $1

  # good
  process Regexp.last_match[1]

避免使用数字化命名分组很难明白他们代表的意思。命名群组来替代。

  # bad
  /(regexp)/ =~ string
  ...
  process Regexp.last_match[1]

  # good
  /(?<meaningful_var>regexp)/ =~ string
  ...
  process meaningful_var

字符类有以下几个特殊关键字值得注意: ^, -, , ], 所以, 不要转义 . 或者 [] 中的括号。

注意, ^ 和 $ , 他们匹配行首和行尾, 而不是一个字符串的结尾, 如果你想匹配整个字符串, 用 A 和 Z。

  string = "some injectionnusername"
  string[/^username$/]  # matches
  string[/AusernameZ/] # don't match

针对复杂的正则表达式,使用 x 修饰符。可提高可读性并可以加入有用的注释。只是要注意空白字符会被忽略。

  regexp = %r{
   start     # some text
   s      # white space char
   (group)    # first group
   (?:alt1|alt2) # some alternation
   end
  }x

sub/gsub 也支持哈希以及代码块形式语法, 可用于复杂情形下的替换操作.

Ruby中的字符串编写示例
优先使用字符串插值来代替字符串串联。#bademail_with_name=user.name+''+user.email+''#goodemail_with_name="#{user.name}#{user.email}"#goodemail_with_name=format('%s%s',user.name,user.em

Ruby元编程的一些值得注意的地方
避免无限循环的元编程。写一个函数库时不要使核心类混乱(不要使用monkeypatch)。代码块形式最好用于字符串插值形式。当你使用字符串插值形式,总

Ruby中百分号和字面值的使用示例
需要插值与嵌入双引号的单行字符串使用%()(是%Q的简写)。多行字符串,最好用heredocs。#bad(nointerpolationneeded)%(divclass="text"Sometext/div)#shouldbe'divclass="text"


编辑:编程语言

标签:字符串,形式,插值,当你,示例