我试图从一个看起来像“ABCDEFG [1]”的字符串中获取数值。在这里,我试图得到1.我尝试在下面的字符串上使用split方法,但dint获得成功。任何解决方案都是值得赞赏的。谢谢!
答案 0 :(得分:0)
你走了:
def get_numeric_value(str)
# Match a number surrounded by square brackets
matchdata = str.match(/\[\d+\]/)
if matchdata
# Get the first matched substring, and remove the first and last characters
# (which will be the square brackets)
number = matchdata[0][1..-2]
number.to_i
else
nil
end
end
get_numeric_value "ABCDEFG [1]" #=> 1