在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] # 提取價格,結(jié)果為 "45"
discount_pattern = /\s*(\d+(?:\.\d{1,2})?)%\s*/
discount = text.match(discount_pattern)[1] # 提取折扣百分比,結(jié)果為 "10"
word_pattern = /\b(\w+)\b/
words = text.scan(word_pattern) # 提取所有單詞,結(jié)果為 ["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] # 提取電話號碼,結(jié)果為 "45"
這些示例展示了如何使用Ruby的正則表達式來提取字符串中的價格、折扣百分比、單詞和電話號碼等信息。你可以根據(jù)需要修改正則表達式以匹配特定的信息。