0

I have a string which is a function call. I want to parse it and obtain the parameters:

"add_location('http://abc.com/page/1/','This is the title, it is long',39.677765,-45.4343,34454,'http://abc.com/images/image_1.jpg')"

It has a total of 6 parameters and is a mixture of urls, integers and decimals. I can't figure out the regex for the split method which I will be using. Please help! This is what I have come up with - which is wrong.

/('(.*\/[0-9]*)',)|([0-9]*,)/

3 Answers 3

3

Treating the string like a CSV might work:

require 'csv'
str = "add_location('http://abc.com/page/1/','This is the title, it is long',39.677765,-45.4343,34454,'http://abc.com/images/image_1.jpg')"
p CSV.parse(str[13..-2], :quote_char => "'").first
# => ["http://abc.com/page/1/", "This is the title, it is long", "39.677765", "-45.4343", "34454", "http://abc.com/images/image_1.jpg"]
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming all non-numeric parameters are enclosed in single quotes, as in your example

string.scan( /'.+?'|[-0-9.]+/ )

2 Comments

Nice Regex! Assuming, the arguments are simple constants - no arithmetic operations or method calls
Great - exactly what i needed. The non-numeric parameters are enclosed in single quotes.
0

You really don't want to be parsing things this complex with a reg-ex; it just won't work in the long run. I'm not sure if you just want to parse this one string, or if there are lots of strings in this form which vary in exact contents. If you give a bit more info about your end goal, you might be able to get some more detailed help.

For parsing things this complex in the general case, you really want to perform proper tokenization (i.e. lexical analysis) of the string. In the past with Ruby, I've had good experiences doing this with Citrus. It's a nice gem for parsing complex tokens/languages like you're trying to do. You can find more about it here:

https://github.com/mjijackson/citrus

Comments

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.