如果只是需要中查找字符串的 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 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 也支持哈希以及代碼塊形式語法, 可用于復雜情形下的替換操作.
新聞熱點
疑難解答
圖片精選