Ruby中的正则表达式是一种非常强大的工具,用于匹配、查找、替换和分割字符串。以下是一些Ruby正则表达式的高效用法:
email = "example@example.com"
if email =~ /\A[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\z/
puts "Valid email address"
else
puts "Invalid email address"
end
text = "I love Ruby programming."
matches = text.scan(/\bRuby\b/)
puts matches.inspect
text = "The price is $10 and the discount is 20%."
replaced_text = text.gsub(/\d+/, "#")
puts replaced_text
sentence = "This is a sample sentence."
words = sentence.split(/\s+/)
puts words.inspect
email = "user@example.com"
match = email.match(/([\w.%]+)@([\w.-]+)\./)
if match
username = match[1]
domain = match[2]
puts "Username: #{username}, Domain: #{domain}"
else
puts "No match found"
end
这些只是Ruby正则表达式的一些基本用法,实际上正则表达式还有很多高级功能和选项,可以根据需要进行更复杂的匹配和操作。