首页 > 解决方案 > 如何从文件中的每一行中提取整数(一年)以及字母和数字的组合

问题描述

我正在开发一个程序,该程序读取包含有关手机的不同类型信息的文件,然后提取并存储每条信息。例如,这是文件中许多行中的两行:

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为年份而不是2015and 2000。我想提取2015WB0126A模型(字母和数字的任何随机组合)而不是12hrsand 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.

标签: ruby

解决方案


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​​ 的正则表达式的确切风格。


推荐阅读