如果只是需要中尋找字串的 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 也支援雜湊以及代碼塊形式文法, 可用於複雜情形下的替換操作.