\"US\", \"ToState\"=>\"AL\", \"SmsMessageSid\"=>\"SMa1a9e3" /> \"US\", \"ToState\"=>\"AL\", \"SmsMessageSid\"=>\"SMa1a9e3" /> \"US\", \"ToState\"=>\"AL\", \"SmsMessageSid\"=>\"SMa1a9e3"/>

What can be the ruby regex for capturing specific value for given string?

39 Views Asked by At

I have a string like below :

"[a06aad57-5671-482e-dbdd81dc39b1]   Parameters: {\"ToCountry\"=>\"US\", \"ToState\"=>\"AL\", \"SmsMessageSid\"=>\"SMa1a9e32a7503f7342b7065d77174d\"}"  

I would like to capture only value of 'Parameters:' as below and convert it to hash. Key/value can be any value in above raw string :

{"ToCountry"=>"US", "ToState"=>"AL", "SmsMessageSid"=>"SMa1a9e32a7503f3767342b7065d77174d"}

2

There are 2 best solutions below

0
Oleksandr Holubenko On BEST ANSWER

You can do it through a few steps:

require 'json'

string = "[a06aad57-5671-482e-dbdd81dc39b1]   Parameters: {\"ToCountry\"=>\"US\", \"ToState\"=>\"AL\", \"SmsMessageSid\"=>\"SMa1a9e32a7503f7342b7065d77174d\"}"
prepared_string = string.match(/Parameters:(.*)/)[1].gsub("=>", ":")
json = JSON.parse(prepared_string)
#=> {"ToCountry"=>"US", "ToState"=>"AL", "SmsMessageSid"=>"SMa1a9e32a7503f7342b7065d77174d"}
0
Alok Swain On

Not via regex and not the best approach evaling a user input but this will do it:

eval str.split("Parameters: ")[1]