簡體   English   中英

JavaScript Regex:獲取匹配項和另一個字符之間的字符串

[英]JavaScript Regex: Get string between a match and another char

我對以下文本和 Regex 方法有疑問。 我從我的服務器(從 Wordpress 數據庫)檢索文本,我想用正則表達式從中提取圖像src

來自服務器的字符串如下所示:

...
[other_directives ...]
[et_pb_image admin_label="Bild" 
    src="http://url.com/wp-content/uploads/2015/08/imageXYZ.jpg"
     show_in_lightbox="off" url_new_window="off" animation="left" sticky="off" align="left" 
    force_fullwidth="off" always_center_on_mobile="on" use_border_color="off" 
    border_color="#ffffff" border_style="solid" alt="some text"]
[other_directives ...]
...

我想搜索et_pb_image字符串並想提取其中src文本的撇號之間的文本。

這可以用純正則表達式嗎?

編輯

到目前為止我嘗試過的(我是正則表達式初學者):

/(et_pb_image)?(src=").+[a-z]/

這將返回 src 但帶有src="..."標簽。

您需要非常小心地使用正則表達式解析此類文本。 幾乎每次我們都必須假設一些東西。 因此,在這種情況下,我們假設在et_pb_imagesrc屬性之間沒有] 此外,我們假設 src 屬性值用"括起來。

然后,您可以使用

 var re = /et_pb_image[^\\]]*?src="([^"]+)"/ig; var str = '...\\n[other_directives ...]\\n[et_pb_image admin_label="Bild" \\n show_in_lightbox="off" url_new_window="off" animation="left" sticky="off" align="left" \\n force_fullwidth="off" always_center_on_mobile="on" use_border_color="off" \\n src="http://url.com/wp-content/uploads/2015/08/imageXYZ.jpg"\\n[other_directives ...]\\n...\\n\\n...\\n[other_directives ...]\\n[et_pb_image admin_label="Bild" \\n src="http://url.com/wp-content/uploads/2015/08/imageXYZ.jpg" border_color="#ffffff" border_style="solid" alt="some text"]\\n show_in_lightbox="off" url_new_window="off" animation="left" sticky="off" align="left" \\n force_fullwidth="off" always_center_on_mobile="on" use_border_color="off" \\n \\n border_color="#ffffff" border_style="solid" alt="some text"]\\n[other_directives ...]\\n...\\n...\\n[other_directives ...]\\n[et_pb_image admin_label="Bild" \\n src="http://url.com/wp-content/uploads/2015/08/imageXYZ.jpg"\\n show_in_lightbox="off" url_new_window="off" animation="left" sticky="off" align="left" \\n force_fullwidth="off" always_center_on_mobile="on" use_border_color="off" \\n border_color="#ffffff" border_style="solid" alt="some text"]\\n[other_directives ...]'; var m; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } document.write(m[1] + "<br/>"); }

正則表達式是/et_pb_image[^\\]]*?src="([^"]+)"/ig匹配

  • et_pb_image - 文字et_pb_image
  • [^\\]]*? - 除]以外的任何字符,盡可能少
  • src=" - 文字src="
  • ([^"]+) - 除了"之外的 1 個或更多字符(假設 src 屬性值始終用雙引號括起來)
  • " -一個字面意思"

我們需要在所有匹配中獲取捕獲的組 1,而使用string.match無法實現,我們必須使用exec

使用javascript:

myLongString.match( /et_pb_image.+\s+src="(.+)"/g )

正則表達式可視化

調試器演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM