在Ruby中,使用正则表达式处理字符串非常常见。以下是一些关于如何在Ruby中使用正则表达式的例子:
- 查找字符串中的匹配项:
str = "Hello, my name is Ruby."
regex = /Ruby/
match = str.match(regex)
if match
puts "Found match: #{match[0]}"
else
puts "No match found"
end
- 查找字符串中所有匹配项:
str = "There are 3 Rubies and 5 Rubies in the basket." regex = /Ruby/gi matches = str.scan(regex) puts "Found #{matches.size} matches:" puts matches.join(', ')
- 替换字符串中的匹配项:
str = "I like cats, cats are cute." regex = /cats/ replacement = "dogs" new_str = str.gsub(regex, replacement) puts "Original string: #{str}" puts "New string: #{new_str}"
- 使用捕获组:
str = "The price of the item is $40."
regex = /\$(\d+)/
matches = str.scan(regex)
if matches
puts "Found matches:"
matches.each do |match|
puts "Price: $#{match[0]}"
end
else
puts "No match found"
end
这些例子展示了如何在Ruby中使用正则表达式处理字符串。你可以根据需要调整正则表达式和替换字符串来完成不同的任务。