【问题标题】:Regex works in textwrangler but something isn't right in my ruby script正则表达式在 textwrangler 中有效,但在我的 ruby​​ 脚本中有些问题
【发布时间】:2012-06-27 12:55:47
【问题描述】:

我可以找人在我的脚本上打孔吗?我的正则表达式可以很好地在 textwrangler 中查找 url,但是当我运行我的脚本时,parseducc.txt 文件会将一些零碎的东西放在不同的行上。

export = File.new("parseducc.txt" , "w+")
File.open("uccdata.txt").each_line do |line|

    line.scan(/(([a-zA-Z0-9-])+\.)+([a-zA-Z]){3,4}/) do |x|
        export.puts x
    end
end

样本输出

dhl-美国。
一个

加价。
t

联邦快递。
x

我的黄色。
w

我使用此脚本的目标是逐行扫描文件并提取 URL 并将它们每行一个转储到新的输出文件中。我已经尝试了这个脚本的几种变体,但显然我遗漏了一些东西。我猜它在我的正则表达式中,但我使用了我在 regexlib.com 上找到的不同变体,它们显示出不同的类似问题。

【问题讨论】:

  • 你能发布你输入文件的内容吗?

标签: ruby regex


【解决方案1】:

试试这个:

export = File.new("parseducc.txt" , "w+") 
File.open("uccdata.txt").each_line do |line| 
  line.scan(/(https?:\/\/\S+)/) do |x| 
    export.puts x 
  end 
end

【讨论】:

  • 这回答了一个问题。这绝对是我的正则表达式。效果很好,只是它在 http(s):// 上键入以识别 url,我需要去掉斜杠、冒号和 http 以仅显示目标的域名。
  • @LillyBean - 如果您只想要域名,请使用/https?:\/\/([-a-z\d.]+)/i
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 2015-04-11
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
相关资源
最近更新 更多