溫馨提示×

Ruby正則表達式怎樣處理字符串

小樊
81
2024-10-24 07:54:30
欄目: 編程語言

在Ruby中,使用正則表達式處理字符串非常常見。以下是一些關(guān)于如何在Ruby中使用正則表達式的例子:

  1. 查找字符串中的匹配項:
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
  1. 查找字符串中所有匹配項:
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(', ')
  1. 替換字符串中的匹配項:
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}"
  1. 使用捕獲組:
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中使用正則表達式處理字符串。你可以根據(jù)需要調(diào)整正則表達式和替換字符串來完成不同的任務(wù)。

0