A quick run of that code:
string source = @"match = {src=""http://www.mertidattleva.se/wp-content/uploads/2013/04/016stor-300x200.jpg}";
Match matchImgTags = Regex.Match(source, @"src\s*=\s*""([^""]+)", RegexOptions.IgnoreCase);
if (matchImgTags.Groups.Count > 0)
{
foreach (Match match in matchImgTags.Groups)
{
var fileName = Path.GetFileName(match.Value);
source = source.Replace(match.Value, fileName);
}
}
else
{
var fileName = Path.GetFileName(matchImgTags.Groups[0].Value);
source = source.Replace(matchImgTags.Value, "");
}
Gives me two matches from the input string:
src="http://www.mertidattleva.se/wp-content/uploads/2013/04/016stor-300x200.jpg}
And the second isn't a match, so the foreach refuses to cast it.
I would go with:
Match matchImgTags = Regex.Match(source, @"src\s*=\s*""([^""]+)", RegexOptions.IgnoreCase);
if (matchImgTags.Success)
{
string s = matchImgTags.Value;
...
}
But even then, the returned match string is not a valid filename, so Path.GetFileName throws an exception.
What you need to do is change the regex:
(?<=src=").+?(?=})
Will probably do it:
string source = @"match = {src=""http://www.mertidattleva.se/wp-content/uploads/2013/04/016stor-300x200.jpg}";
Match matchImgTags = Regex.Match(source, @"(?<=src="").+?(?=})", RegexOptions.IgnoreCase);
if (matchImgTags.Success)
{
string s = matchImgTags.Value;
string fileName = Path.GetFileName(s);
source = source.Replace(s, fileName);
}
"I am a beginner to regex, downloaded espresso put in this string:
?<=src="").+?(?=["}])
but don't know what's wrong"
:sigh:
You have two separate systems here: regex and C# strings.
When you enter a C# string, it starts and ends with a double quote:
string s = "hello user this is a string";
If you want to include a double quote in the string, you have two ways to do it:
string s1 = "hello \"user\" this is a string";
string s2 = @"hello ""user"" this is a string";
but Regexs don't regard double quote as a special character at all - they do with backslash - so a regexes that contains a double quote:
... =src").+?( ...
Don't need any special processing.
Unless...you want to use a C# string as input to a regex:
string s = @"... =src"").+?( ...";
So if you take a C# string and you paste it into Expresso (which deals with regexes, not C# strings) you have to manually "un-special case" it and condense doubled double quotes to single double quotes. Exactly as if you manually pasted it into Word, or Notepad, or any other app that doesn't work with C# strings (i.e. most of them!)
Make sense now?