Simple Ruby Regex for JSON string
I have the following simple JSON string:
{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}
and I'd like to extract each number in the array following "exclude". 开发者_开发百科 In other words, I'd expect my 0th match to be all numbers, my first match to be 4, my second 5, and so on. Many thanks.
Maybe not a single neat regex like you might hope for:
s = '{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}'
all_numbers = s[/\[[\d,\s]+\]/]
# => "[4, 5, 6, 10]"
all_numbers.scan(/\d+/).map { |m| m.to_i }
# => [4, 5, 6, 10]
# Depends how much you trust the regex that grabs the result for all_numbers.
eval(all_numbers)
# => [4, 5, 6, 10]
# As a one-liner.
s[/\[[\d,\s]+\]/].scan(/\d+/).map { |m| m.to_i } # => [4, 5, 6, 10]
if i really had to use regexps here, i would do something like this:
string = "{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}"
exclude, include = string.scan(/(\[[\d,\s]{0,}\])/).map {|match| eval match.first}
exclude # => [4, 5, 6, 10]
include # => []
As pointed by DigitalRoss, your String does not contain JSON, but apparently plain Ruby code.
You can easily evaluate it and access it simply:
lStr = "{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}"
# Evaluate the string: you get a map
lMap = eval(lStr)
# => {"exclude"=>[4, 5, 6, 10], "include"=>[]}
# Read the properties
lMap['exclude']
# => [4, 5, 6, 10]
lMap['include']
# => []
lMap['exclude'][2]
# => 6
精彩评论