簡體   English   中英

Ruby正則表達式解析命令行

[英]Ruby regexp to parse command line

像許多命令行實用程序一樣,如何在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),它應該產生正則表達式。

好的,我發現optparse可以為我做

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM