【发布时间】: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),它应该产生正则表达式。
【问题讨论】: