红宝石 |正则表达式 escape()函数
Regexp#escape() :escape()是一个 Regexp 类方法,它通过转义任何在正则表达式中具有特殊含义的字符来返回一个新字符串。
Syntax: Regexp.escape()
Parameter: Regexp values
Return: a new string by escaping any characters that would have special meaning in a regular expression.
示例 #1:
# Ruby code for Regexp.escape() method
# declaring Regexp value
reg_a = Regexp.escape('/a/')
# declaring Regexp value
reg_c = Regexp.escape('\*?{}.')
# escape method
puts "Regexp escape form : #{reg_a}\n\n"
puts "Regexp escape form : #{reg_c}\n\n"
输出 :
Regexp escape form : /a/
Regexp escape form : \\\*\?\{\}\.
示例 #2:
# Ruby code for Regexp.escape() method
# declaring Regexp value
reg_a = Regexp.escape('/geeks/')
# declaring Regexp value
reg_b = Regexp.escape('/(?.)(?.)(?.)/')
# declaring Regexp value
reg_c = Regexp.escape('\*?????{}.')
# escape method
puts "Regexp escape form : #{reg_a}\n\n"
puts "Regexp escape form : #{reg_b}\n\n"
puts "Regexp escape form : #{reg_c}\n\n"
输出 :
Regexp escape form : /geeks/
Regexp escape form : /\(\?\.\)\(\?\.\)\(\?\.\)/
Regexp escape form : \\\*\?\?\?\?\?\{\}\.