在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中使用正則表達式處理字符串。你可以根據需要調整正則表達式和替換字符串來完成不同的任務。