开发者

Ruby regexp to parse command line

开发者 https://www.devze.com 2023-01-01 18:38 出处:网络
How can I parse strings in ruby like many command line utilities do? I\'ve got strings similar to \"command [--opt1=...] [--enable-opt2] --opt3=... arg1\" and methods similar to command(opt1,opt2,opt3

How can I parse strings in ruby like many command line utilities do? I've got strings similar to "command [--opt1=...] [--enable-opt2] --opt3=... arg1" and methods similar to command(opt1,opt2,opt3,arg1...). I want to let arguments to come in random order, some of them can be optional.

At the moment I wrilte regexp every time I need to parse new command, as for example to parse "lastpost --chan=your_CHANNEL /section/"

I have this regular expression:

    text = "lastpost --chan=0chan.ru /s/"
    command = (tex开发者_开发技巧t.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

I wish i had create_regexp(opts,args), which should produce regular expression.


Ok, I found optparse can do it for me

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号