【问题标题】:Ruby regexp to parse command lineRuby正则表达式解析命令行
【发布时间】:2010-06-03 00:33:51
【问题描述】:

如何像许多命令行实用程序一样在 ruby​​ 中解析字符串?我有类似于"command [--opt1=...] [--enable-opt2] --opt3=... arg1" 的字符串和类似于command(opt1,opt2,opt3,arg1...) 的方法。我想让参数以随机顺序出现,其中一些可以是可选的。

目前我每次需要解析新命令时都会编写正则表达式,例如 解析“lastpost --chan=your_CHANNEL /section/”

我有这个正则表达式:

    text = "lastpost --chan=0chan.ru /s/"
    command = (text.match /^\w+/)[0]
    args = text.gsub(/^\w+/,'')
    if args =~ /[[:blank:]]*(--chan\=([[:graph:]]+)[[:blank:]]+)*\/?(\w+)\/?/
        chan = $2
        section = $3
        do_command(chan,section)
    else
        puts "wrong args"
    end

我希望我有 create_regexp(opts,args),它应该产生正则表达式。

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    好的,我发现optparse 可以为我做这件事

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2013-11-01
      • 1970-01-01
      • 2014-06-22
      • 2012-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多