Ruby regexp to parse command line

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 = (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

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

Answers


Ok, I found optparse can do it for me


Need Your Help

In CakePHP 2.x ORM + use Function MySQL AND NameClass Models remove ;(

php mysql cakephp orm model

Problem, how to make the ORM CakePHP, do not waste my table name or class, when a flame fied with a mysql function for example SUM() "sum(SenasaPedidosDetalles.kg_reales) total_kg_reales".

for each selected listitem

delphi listview listitem

I try to do an action for each selected listitem but it won't work.