gpt4 book ai didi

regex - 用于替换 html标签中SRC内容的内容的正则表达式

转载 作者:行者123 更新时间:2023-12-03 18:26:05 24 4
gpt4 key购买 nike

我对正则表达式不太满意,因此我希望您能通过一个表达式来帮助我,以便仅替换html标签src属性中双引号之间的内容,即该属性的内容如下:

TRegEx.Replace(Str, '(?<=<img\s+[^>]*?src=(?<q>[""]))(?<url>.+?)(?=\k<q>)', 'Nova string');


换句话说:src =“ old content” => src =“ new content

在上面有关C#中相同主题的问题中,我已经看到了此表达式,但是不适用于Delphi。

那么,该怎么做呢?

提前谢谢。

最佳答案

正则表达式:

<img(.*?)src="(.*?)"(.*?)/>


替代:

<img$1src="NEW VALUE"$3/>




您可以使用类似:

var
ResultString: string;

ResultString := '';
try
ResultString := TRegEx.Replace(SubjectString, '<img(.*?)src="(.*?)"(.*?)/>', '<img$1src="NEW VALUE"$3/>', [roIgnoreCase, roMultiLine]);
except
on E: ERegularExpressionError do begin
// Syntax error in the regular expression
end;
end;




正则表达式说明:

<img(.*?)src="(.*?)"(.*?)/>

Options: Case insensitive; Exact spacing; Dot doesn’t match line breaks; ^$ match at line breaks; Numbered capture; Allow zero-length matches

Match the character string “<img” literally (case insensitive) «<img»
Match the regex below and capture its match into backreference number 1 «(.*?)»
Match any single character that is NOT a line break character (line feed, carriage return, form feed, vertical tab, next line, line separator, paragraph separator) «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “src="” literally (case insensitive) «src="»
Match the regex below and capture its match into backreference number 2 «(.*?)»
Match any single character that is NOT a line break character (line feed, carriage return, form feed, vertical tab, next line, line separator, paragraph separator) «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “"” literally «"»
Match the regex below and capture its match into backreference number 3 «(.*?)»
Match any single character that is NOT a line break character (line feed, carriage return, form feed, vertical tab, next line, line separator, paragraph separator) «.*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character string “/>” literally «/>»

<img$1src="NEW VALUE"$3/>

Insert the character string “<img” literally «<img»
Insert the text that was last matched by capturing group number 1 «$1»
Insert the character string “src="NEW VALUE"” literally «src="NEW VALUE"»
Insert the text that was last matched by capturing group number 3 «$3»
Insert the character string “/>” literally «/>»




Regex101 Demo

关于regex - 用于替换<IMG> html标签中SRC内容的内容的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37081400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com