Varin
Varin

Reputation: 119

Regular Expression to match image path and replace with another

Using Regular Expressions, I am struggling to figure out how to match an image source pattern within HTML document, and replace it with a different path:

Replace source like this:

img alt="description" align=left src="/xxxx/ssss/sssss/sssss/Photos/myimage.jpg"

with like this:

img alt="description" align=left src="http://www.mysite.com/subsite/images/myimage.jpg"

keeping the same image name.

Upvotes: 1

Views: 693

Answers (2)

Victor Dodon
Victor Dodon

Reputation: 1864

You may try this:

/<img\s+([^s]\w+=\"[^"]+\"\s+)*src=\"([^"]+)\"\s+(\w+=\"[^"]+\"\s+)*\/>/i

and the image src will be kept in \2, where \w means any word character (letter, number, underscore), and \s means any space character. This regex will match src even if it is not the third attribute.

You may try this on rubular.com to see how it works.

Upvotes: 0

ikegami
ikegami

Reputation: 385506

Search pattern:

img alt="description" align=left src="\K[^"]*(?=")

Replace match with following value:

http://www.mysite.com/subsite/images/myimage.jpg

(Sorry, don't know C#.)

Upvotes: 0

Related Questions