Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有这个:
author = m.match(/Author: (\w*)/)[1].strip
它有时会给我一个“未定义的方法[]”异常
如果正则表达式不匹配,分配固定值(例如“”或“未找到”)的最佳方法是什么?也许救援?
最好的方法是:
author = m[/regex/, 1] || "not found"
鲁比真的不可思议。
def find_author s s =~ /Author: (\w*)/ ? $1 : 'not found' end find_author 'Author: Joe' # => "Joe" find_author 'No author here' # => "not found"