在Ruby中,使用正则表达式(Regular Expression)可以轻松地提取字符串中的特定信息。以下是一些基本示例,说明如何使用Ruby的正则表达式来提取信息:
re
模块:require 're'
text = "The price of the item is $45 and the discount is 10%."
price_pattern = /\$(\d+(?:\.\d{1,2})?)/
price = text.match(price_pattern)[1] # 提取价格,结果为 "45"
discount_pattern = /\s*(\d+(?:\.\d{1,2})?)%\s*/
discount = text.match(discount_pattern)[1] # 提取折扣百分比,结果为 "10"
word_pattern = /\b(\w+)\b/
words = text.scan(word_pattern) # 提取所有单词,结果为 ["The", "price", "of", "the", "item", "is", "$45", "and", "the", "discount", "is", "10%"]
phone_pattern = /\b(\d{3})[-. ](\d{3})[-. ](\d{4})\b/
phone_number = text.match(phone_pattern)[1] # 提取电话号码,结果为 "45"
这些示例展示了如何使用Ruby的正则表达式来提取字符串中的价格、折扣百分比、单词和电话号码等信息。你可以根据需要修改正则表达式以匹配特定的信息。