在Ruby中使用正则表达式非常简单,可以使用=~或者match方法来匹配正则表达式。
=~操作符:str = "Hello, World!"if str =~ /Hello/ puts "Matched!"else puts "Not matched"end使用match方法:str = "Hello, World!"if /Hello/.match(str) puts "Matched!"else puts "Not matched"end除了匹配,还可以使用正则表达式来替换字符串中的内容:
str = "Hello, World!"new_str = str.gsub(/Hello/, "Hi")puts new_str以上就是在Ruby中使用正则表达式的基本方法,通过这些方法可以方便地对字符串进行匹配和替换操作。




