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正則表達式的一些基本用法,實際上正則表達式還有很多高級功能和選項,可以根據需要進行更復雜的匹配和操作。