0

I have the string "{:name=>\"entry 1\", :description=>\"description 1\"}"

I'm using regex to get the values of name and description...

string = "{:name=>\"entry 1\", :description=>\"description 1\"}"

name = /\:name=>\"(.*?)\,/.match(string)
description = /\:description=>\"(.*?)\,/.match(string)

This however only returns name as #<MatchData ":name=>\"entry 1\"," 1:"entry 1\""> and description comes back as nil.

What I ideally want is for name to return "entry 1" and description come back as "description 1"

I'm not sure where I'm going wrong... any ideas?

3
  • which language are you using ? Commented May 21, 2015 at 16:12
  • Ruby and Ruby on Rails Commented May 21, 2015 at 16:13
  • Not what you are looking for, but note: eval(string).values #=> ["entry 1", "description 1"] . Commented May 21, 2015 at 16:25

2 Answers 2

1

The problem is the comma in /\:description=>\"(.*?)\,/ should be /\:description=>\"(.*?)/ or /\:description=>\"([^"]+)/

Also you can this method:

def extract_value_from_string(string, key)
  %r{#{key}=>\"([^"]+)}.match(string)[1]
end

extract_value_from_string(string, 'description')
=> "description 1"
extract_value_from_string(string, 'name')
=> "name 1"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.... I ended up just using /\:description=>\"([^"]+)/.match(string) and it worked like a charm. Thanks!
0

try this regex to retrieve both name and description at one step

(?<=name=>\\"|description=>\\")[^\\]+

try this Demo

I know this demo is using PCRE but I've tested also on http://rubular.com/ and it works fine

and if you want to get them separately use this regex is to extract name (?<=name=>\\")[^\\]+ and this for description (?<=description=>\\")[^\\]+

1 Comment

Not sure why but it works in Rubular but in my controller when I try p description = /(?<=description=>\\")[^\\]+/.match(string) it returns nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.