淺析Ruby中的Regex的使用_ruby專題

來源:互聯網
上載者:User


    如果只是需要中尋找字串的 text, 不要使用Regex: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 injection\nusername"  string[/^username$/]  # matches  string[/\Ausername\Z/] # don't match

    針對複雜的Regex,使用 x 修飾符。可提高可讀性並可以加入有用的注釋。只是要注意空白字元會被忽略。

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

    sub/gsub 也支援雜湊以及代碼塊形式文法, 可用於複雜情形下的替換操作.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.