欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺析Ruby中的正則表達(dá)式的使用

 更新時(shí)間:2015年08月03日 16:05:27   投稿:goldensun  
這篇文章主要介紹了淺析Ruby中的正則表達(dá)式的使用,作者根據(jù)Ruby對(duì)正則表達(dá)式的支持提出了其中一些需要注意的地方,需要的朋友可以參考下


    如果只是需要中查找字符串的 text, 不要使用正則表達(dá)式:string['text']

    針對(duì)簡(jiǎn)單的結(jié)構(gòu), 你可以直接使用string[/RE/]的方式來(lái)查詢.

  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'

    當(dāng)你不需要替結(jié)果分組時(shí),使用非分組的群組。

  /(first|second)/  # bad
  /(?:first|second)/ # good

    不要使用 Perl 遺風(fēng)的變量來(lái)表示匹配的正則分組(如 $1,$2 等),使用 Regexp.last_match[n] 作為替代。

  /(regexp)/ =~ string
  ...

  # bad
  process $1

  # good
  process Regexp.last_match[1]

    避免使用數(shù)字化命名分組很難明白他們代表的意思。命名群組來(lái)替代。

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

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

    字符類有以下幾個(gè)特殊關(guān)鍵字值得注意: ^, -, \, ], 所以, 不要轉(zhuǎn)義 . 或者 [] 中的括號(hào)。

    注意, ^ 和 $ , 他們匹配行首和行尾, 而不是一個(gè)字符串的結(jié)尾, 如果你想匹配整個(gè)字符串, 用 \A 和 \Z。

  string = "some injection\nusername"
  string[/^username$/]  # matches
  string[/\Ausername\Z/] # don't match

    針對(duì)復(fù)雜的正則表達(dá)式,使用 x 修飾符??商岣呖勺x性并可以加入有用的注釋。只是要注意空白字符會(huì)被忽略。

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

    sub/gsub 也支持哈希以及代碼塊形式語(yǔ)法, 可用于復(fù)雜情形下的替換操作.

相關(guān)文章

最新評(píng)論