Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用正则表达式从href属性获取链接_Javascript_Regex_Google Apps Script - Fatal编程技术网

Javascript 如何使用正则表达式从href属性获取链接

Javascript 如何使用正则表达式从href属性获取链接,javascript,regex,google-apps-script,Javascript,Regex,Google Apps Script,我有一个regex表达式,它返回html文件中的所有链接,但它有一个问题:不是只返回链接,比如http://link.com,它还返回href=“(href=”http://link.com)。我如何才能只获取链接,而不获取href=“ 这是我的正则表达式: /href="(http|https|ftp|ftps)\:\/\/[-a-zA-Z0-9.]+\.[a-zA-Z]{2,3}(?:\/(?:[^"<=]|=)*)?/g /href=“(http | https | ftp | f

我有一个
regex
表达式,它返回html文件中的所有链接,但它有一个问题:不是只返回链接,比如
http://link.com
,它还返回href=“(
href=”http://link.com
)。我如何才能只获取
链接
,而不获取
href=“

这是我的正则表达式:

/href="(http|https|ftp|ftps)\:\/\/[-a-zA-Z0-9.]+\.[a-zA-Z]{2,3}(?:\/(?:[^"<=]|=)*)?/g
/href=“(http | https | ftp | ftps)\:\/\/[-a-zA-Z0-9.]+\.[a-zA-Z]{2,3}(?:\/(?:[^”
RegExp#exec
将存储模式中定义的捕获组捕获的所有内容。您可以使用
[1]
索引访问组1

使用

另外,我相信你可以把正则表达式缩短到

/\bhref="((?:http|ftp)[^"]+)"/g

如果您确定值总是在双引号内。请参阅。

为什么要使其复杂化?
/href=“([^”]+)”/g
(如果您知道输入总是在双引号中包含属性值)您不应该用正则表达式解析HTML。请使用适当的解析器。或者。@WiktorStribiżew我尝试过这个,但它也会返回电子邮件地址,我不需要this@Amadan我从电子邮件中获取正文内容(HTML格式),响应类型为字符串。因此,我有一个包含HTML属性的字符串:)没问题,只需添加
http
/href=“(http:\/\/[^”]+)"/g
。无论如何,您的正则表达式看起来像JS,在JS中,我宁愿使用DOM来获取所有的HREF,并保留那些以
http
开头的HREF。正则表达式对于任意HTML内容的这种类型的工作并没有真正的帮助。我修改了代码,在您的帮助下,结果得到了改进,但仍然有一个问题……现在链接有
>“
之前(如下所示:
”https://link.com
)这是不可能的,只需记录
matchArray[1]
值。你可以在引号中获得它,因为你
JSON.stringify
它。你是对的,
JSON.stringify
把事情搞砸了,现在一切都正常了!
var token = matchArray[1];
/\bhref="((?:http|ftp)[^"]+)"/g