dqf42223 2015-12-22 20:42
浏览 58
已采纳

使用xpath查询将xpath正则表达式捕获组作为字符串返回

CONTEXT

Supposing the following HTML

....
<p>Whatever</p>
<div>Whatever DIV78232 Everwhat</div>
....

Question:

How could I return a plain text string containing DIVnnnnn, where nnnnn represents any digits.

My investigation so far:

The xPath replace() function will replace a pattern found inside the current DOM.

replace(.,'.*?(DIV\d+).*','$1') => DIV78232

Why am I blocked?

Because I want the query to return the "DIV78232" as a string, without actually replacing it in the DOM at all, just as it would return "Whatever" for the query /p/text() [I am trying all this on the FirePath firefox-extension]

Note: According to the official DOCS

"replace() Returns the value of the first argument with every substring matched by the regular expression that is the value of the second argument replaced by the replacement string that is the value of the third argument."

FINAL PURPOSE:

My final purpose is to get the (string) IMAGE URL that matches '.*?image:.*?"(.+?)".*' from this (which is inside the HTML):

In this case, the query //*[matches(.,'.*?image:.*?"(.+?)".*','i')] returns the whole node, but I only want the first Capturing Group, which would be the IMAGE URL.

<script>...vp&output=xml_vast2&unviewed_position_start=1&
url='+encodeURIComponent(location.href)+'
description_url='+encodeURIComponent(location.href)+'&
image:   "https://domain.com/xxxxxxx/public_images/2015.12/article/56797be1c46188ac438b45c3.jpg", // stretching: 'fi..</script>
  • 写回答

1条回答 默认 最新

  • dongyan2469 2015-12-22 22:17
    关注

    Took me a long while, but this is the result I got by combinating replace() and tokenize()

    tokenize(replace(.,'.*?image:.*?"(.+?)".*?',':@:$1:@:'),':@:')[2]

    Returns the image URL in the snippet above mentioned.

    Why/How does this work?

    • Replace() matches the image and wraps the capturing group with my own token separator ':@:' (Could be anything original)
    • Tokenize() splits the replaced string in 3 parts, being the second one the capturing group I was looking for. (It will be three parts because it is highly improbable that the document will contain ':@:' anywhere else)

    Is there any faster way to achieve this?

    Thanks. All the best. Peace.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料