简体   繁体   中英

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.

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#.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM