用于替换 html 标记中 SRC 内容内容的正则表达式<IMG>



我不太擅长正则表达式,所以我想让你帮我创建一个表达式,只替换html标签src属性中双引号之间的内容,即该属性的内容,类似于以下内容:

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

换句话说:src="old content"=>src="new content"

我在C#中的一个关于同一主题的问题中看到了这个表达式,但不适用于Delphi。

那么,这是怎么做到的呢?

提前Thx。

Regex:

<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;

Regex解释:

<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演示

解决方案:

    procedure CHANGE_IMAGES(Document: IHTMLDocument2);
    var
      I: Integer;
      HTMLImgElement: IHTMLImgElement;
      HTMLElementCollection: IHTMLElementCollection;
    begin
      HTMLElementCollection := Document.images;
      for I := 0 to HTMLElementCollection.length - 1 do
      begin
        HTMLImgElement := (HTMLElementCollection.item(I, 0) as IHTMLImgElement);
        HTMLImgElement.src := 'My_IMAGE_PATH_OR_URL';
        Exit;
      end;
    end;

相关内容

最新更新