ruby - 如何从文件中的每一行中提取整数(一年)以及字母和数字的组合
问题描述
我正在开发一个程序,该程序读取包含有关手机的不同类型信息的文件,然后提取并存储每条信息。例如,这是文件中许多行中的两行:
12hrs,Smartphone,2015WB0126A,used,Apple,2000$,{Bluetooth,Water resistant,fingerprint reader,16GB},white,2016
Used,Smartwatch,Samsung,{activity tracker,Bluetooth,water resistant},2017,250$,black,3947t4f,9hrs
在上面的第一行中,我想提取2016
为年份而不是2015
and 2000
。我想提取2015WB0126A
模型(字母和数字的任何随机组合)而不是12hrs
and 2000$
。有人可以帮我弄这个吗?非常感谢。
f = File.open("listings.txt", "r")
f.each_line do |line|
puts line
year=line[/20+[0-9]+[0-9]/]
puts "made in #{year}"
end
对于示例中的第一行,我希望年份相等2016
,模型为2015WB0126A
.
解决方案
f.each_line do |line|
# find 20xx proceeded by line start or a comma,
# and followed line end or a comma.
# ?: makes the group non-capturing
year = line.match(/(?:^|,)(20\d{2})(?:$|,)/)
year = year[1] if year
model = line.split(',').select do |s|
# 7-30 word characters in length
s =~ /^\w{7,30}$/ &&
# at least 5 digits anywhere in the word
s =~ /(\d.*){5}/
end
puts "#{model.first} made in #{year}"
end
希望该模型有一些合理的限定词可以与您的其余数据一起使用,因为这些限定词非常幼稚。
https://regex101.com/可以对任何正则表达式进行详细解释,如果您想详细了解它们的工作原理。您还可以使用https://rubular.com/来测试 ruby 的正则表达式的确切风格。
推荐阅读
- c++ - 用于透视的倒置几何 gBuffer 位置。正字法好吗?
- python - 蟒蛇 | 制作列表的百分比
- bluetooth - 与 Arduino 的 GPS 通信
- php - 无需大量代码即可将 PHP 插入代码网页设计中。解决了
- uml - 类图到序列图规则
- reactjs - 在 onClick 函数中调用更新函数时 useState 不重新渲染
- swift - ScrollView 中的 SwiftUI Picker 不正确
- python - 独立运行python包子模块进行自检;导入路径组合
- spring-boot - Grpc Spring Boot 启动器
- verilog - 如何在测试台的真值表中分配 Don't Care 值?