Lucas
Lucas

Reputation: 3502

How to get numbers with prefix?

I have a single line of text that looks like

"{\"Title\":\"Die Hard\",\"Year\":\"1988\",\"Rated\":\"R\",\"Released\":\"22 Jul 1988\",\"Runtime\":\"2 h 11 min\",\"Genre\":\"Action, Thriller\",\"Director\":\"John McTiernan\",\"Writer\":\"Roderick Thorp, Jeb Stuart\",\"Actors\":\"Bruce Willis, Alan Rickman, Bonnie Bedelia, Reginald VelJohnson\",\"Plot\":\"John McClane, officer of the NYPD, tries to save wife Holly Gennaro and several others, taken hostage by German terrorist Hans Gruber during a Christmas party at the Nakatomi Plaza in Los Angeles.\",\"Poster\":\"http://ia.media-imdb.com/images/M/MV5BMTY4ODM0OTc2M15BMl5BanBnXkFtZTcwNzE0MTk3OA@@._V1_SX300.jpg\",\"imdbRating\":\"8.3\",\"imdbVotes\":\"401,995\",\"imdbID\":\"tt0095016\",\"Type\":\"movie\",\"Response\":\"True\"}"

And I want to catch the imdbID part

\"imdbID\":\"tt0095016\"

My code looks like

var regex = new Regex("\"imdbID\":\"tt^[0-9]$\"");
var matches = regex.Matches(response);

But I don't get any matches - why? And what would be the correct pattern?

Upvotes: 0

Views: 140

Answers (2)

online Thomas
online Thomas

Reputation: 9381

use

string imdbID = s.Split(new string[]{ "\"imdbID\":\" }, StringSplitOptions.None)[1];
imdbID = imdbID.split(',')[0];

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208505

What you have is JSON, it would really be best to parse this data with a JSON parser rather than regex.

That being said, I don't really have any familiarity with C# so here is how you can fix your regex solution:

var regex = new Regex("\"imdbID\":\"tt[0-9]+\"");
var matches = regex.Matches(response);

The ^ and $ in your current regex definitely need to be removed, these are beginning and end of string anchors so it doesn't make sense to ever have them in the middle of a regular expression (unless perhaps you are matching multiple lines with a multiline option). The other change was to change [0-9] to [0-9]+, the + means "repeat the previous element one or more times", so [0-9]+ will match any number of digits.

Upvotes: 3

Related Questions