views:

52

answers:

2
"artistName":"Travie McCoy", "collectionName":"Billionaire (feat. Bruno Mars) - Single", "trackName":"Billionaire (feat. Bruno Mars)",

i wish to get the artist name so Travie McCoy from within that code using regex, please not i am using regexkitlite for the iphone sdk if this changes things.

Thanks

+2  A: 

"?artistName"?\s*:\s*"([^"]*)("|$) should do the trick. It even handles some variations in the string:

  • White space before and after the :
  • artistName with and without the quotes
  • missing " at the end of the artist name if it is the last thing on the line

But there will be many more variations in the input you might encounter that this regex will not match.

Also you don’t want to use a regex for matching this for performance reasons. Right now you might only be interested in the artistName field. But some time later you will want information from the other fields. If you just change the field name in the regex you’ll have to match the whole string again. Much better to use a parser and transform the whole string into a dictionary where you can access the different fields easily. Parsing the whole string shouldn’t take much longer than matching the last key/value pair using a regex.

This looks like some kind of JSON, there are lots of good and complete parsers available. It isn’t hard to write one yourself though. You could write a simple recursive descent parser in a couple of hours. I think this is something every programmer should have done at least once.

Sven
Thanks for this it kinda worked i got, and yes i wrote my own xml parser. but i just couldnt be arsed with this
Awesome man thanks :), and yes i have written my own parser, i did a xml one i bloody hate the nsxmlparser :)
A: 
\"?artistName\"?\s*:\s*\"([^\"]*)(\"|$)

Thats for objective c