avb
avb

Reputation: 1558

ASP.NET MVC: Match regex multiple times

Regex: ^.*?(?=;)
Value: 00574/KVMK0224.jpg; 00574/1987432370PHANWHCO00MM.jpg
Now only matches: 00574/KVMK0224.jpg
Want: 00574/KVMK0224.jpg and 00574/1987432370PHANWHCO00MM.jpg

As I try to explain shortly I have a string with multiple image links, I made it working to get the first link, but now I want all links. I know how to use regex.Matches in C# to get multiple matches, the only thing I want to know is what regex to use for this.

What I have to get the first link:

    Regex regex = new Regex("^.*?(?=;)");
    Match match = regex.Match(link);
    if (match.Success)
    {
      part.ImageUrl = match.Value;
    }

What I made in order to get all links, I think everything is right on this exept of course the regex

    Regex regex = new Regex("^.*?(?=;)");
    foreach (Match match in regex.Matches(link))
    {
      list.Add(match.Value);
    }

Probably very simple to do this, but I don't have much experience with regexes.

Thanks in advance!

Upvotes: 0

Views: 1457

Answers (2)

Rui Jarimba
Rui Jarimba

Reputation: 17979

If all values are separated by ; then you don't need a regular expression. Try this:

string imagesString = "....";
string[] images = imagesString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

Edit: Here you have an alternativ that uses regular expressions and handles white-space:

string imagesText = "00574/KVMK0224.jpg; 00574/1987432370PHANWHCO00MM.jpg";
string[] images = Regex.Split(imagesText, @"\s*;\s*");

This will work with or without white-space before or after ;

Upvotes: 3

mdelpeix
mdelpeix

Reputation: 187

Perhaps you can try this one ?

[\w/]*?.jpg(?=;)?

Upvotes: 1

Related Questions