-1

I need some guidance on how to do the following.. Let say I have this string below s= {"name":testName,"age":20}

how should I construct my regular expression in ruby, such that I am able to get "testName" Thank you in advance

user486174
  • 41
  • 1
  • 10

2 Answers2

2

The data you have is a JSON string. You should not parse it with a regular expression, but parse it into an object and then access the name property.

I am not a Ruby dev, but you can do so if you have the JSON gem.

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1

I agree with Jason about using JSON, but if you really can't...

1.9.3p194 > s= '{"name":testName,"age":20}'
 => "{\"name\":testName,\"age\":20}" 
1.9.3p194 > s =~ /"name":(.*?)(,"|})/
 => 1 
1.9.3p194 > puts $1
testName

Note that this is evil and wrong and will probably hurt little kittens... use JSON to save the kittens.

Philip Hallstrom
  • 19,673
  • 2
  • 42
  • 46