创建正则表达式
# 使用斜杠包裹正则表达式
pattern = /hello/
# 或者使用 Regexp.new
pattern = Regexp.new("hello")
匹配字符串
pattern = /hello/
str = "hello, world!"
if str =~ pattern
puts "Match found!"
else
puts "Match not found."
end
匹配和捕获
# 使用捕获组
pattern = /(\d+)-(\d+)-(\d+)/
date = "2023-12-25"
match = pattern.match(date)
if match
puts "Year: #{match[1]}, Month: #{match[2]}, Day: #{match[3]}"
else
puts "No match found."
end
字符类和量词
# 字符类
pattern = /[aeiou]/
vowel = "a"
if vowel =~ pattern
puts "Vowel found!"
else
puts "Not a vowel."
end
# 量词
pattern = /\d{3}/
digits = "12345"
match = pattern.match(digits)
if match
puts "Match found: #{match[0]}"
else
puts "No match found."
end
替换字符串
pattern = /world/
str = "hello, world!"
new_str = str.sub(pattern, "Ruby")
puts new_str
# 输出:hello, Ruby!
使用正则表达式进行迭代
pattern = /\d+/
str = "There are 3 numbers in this string."
str.scan(pattern) do |match|
puts "Match found: #{match}"
end
# 输出:
# Match found: 3
正则表达式选项
# 忽略大小写
pattern = /hello/i
str = "HeLLo, World!"
if str =~ pattern
puts "Match found!"
else
puts "Match not found."
end
这是 Ruby 正则表达式的一些基本用法。正则表达式是强大而灵活的工具,用于处理字符串模式匹配。
转载请注明出处:http://www.zyzy.cn/article/detail/13442/Ruby