1

I have a string which contains a link that looks like this:

string source = "<img src='ftp://c//hafiz hussain//appdata//images//image.bmp' />"

I used the following regex to remove the src content:

string regexSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
MatchCollection matchesImgSrc = Regex.Matches(source , regexSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);

This is working fine, only if the folder name has no spaces. For the above case the matchesImgSrc[1].Groups[1].Value matches only till 'ftp://c//hafiz'

Content after the whitespace is ignored.

1
  • 1
    remove th space from the char class. And it's better to use an html parser. Commented May 14, 2015 at 10:03

2 Answers 2

1
<img[^>]*?src\s*=\s*[""']?([^'"">]+?)['""][^>]*?>

You can try this.See demo.

https://regex101.com/r/mT0iE7/22

Sign up to request clarification or add additional context in comments.

Comments

1

As I can see you have an XML-compliant HTML. Thus, I'd suggest using XElement to do that task.

var source = "<img src='ftp://c//hafiz hussain//appdata//images//image.bmp' />";
var elt2 = XElement.Parse(source);
var imgs = elt2.DescendantsAndSelf("img");
foreach (var im in imgs)
{
    var att = im.Attributes().Where(p => p.Name.LocalName.ToLower() == "src");
    if (att != null)
    {
       im.SetAttributeValue("src", string.Empty);
    }
}
// Converting back to string to see the result
var resst = elt2.ToString();

Output:

enter image description here

A regex solution can be used as a fallback:

var source = "<img src='ftp://c//hafiz hussain//appdata//images//image.bmp' />";
var regexSrc = @"(?<=<img[^>]*?)src\s*=\s*[""']?([^'"">]+)[ '""](?=[^>]*?>)";
var reslt = Regex.Replace(source, regexSrc, "src=\"\"");

Output: <img src="" />

1 Comment

If I were you I'd use the solution based on XElement as the main one, and the regex solution only in case of improper/invalid XML.

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.