[英]Extract url from a string with regex in shell script
我需要提取一个用<strong>
标签包装的URL。 这是一个简单的正则表达式,但我不知道如何在shell脚本中这样做。 这是一个例子:
line="<strong>http://www.example.com/index.php</strong>"
url=$(echo $line | sed -n '/strong>(http:\/\/.+)<\/strong/p')
我需要$url
变量中的“http://www.example.com/index.php”。
使用busybox。
这可能有效:
url=$(echo $line | sed -r 's/<strong>([^<]+)<\/strong>/\1/')
url=$(echo $line | sed -n 's!<strong>\(http://[^<]*\)</strong>!\1!p')
您不必使用反斜杠转义正斜杠。 只需要在正则表达式中转义反斜杠。 你还应该使用非贪心匹配?
-operator,以避免在HTML源代码中存在多个强标记时获得超出您想要的内容。
strong>(http://.+?)</strong
更新:由于busybox
使用ash
,假设bash
功能的解决方案可能无效。 东西只有一点点但仍然符合POSIX标准会起作用:
url=${line#<strong>} # $line minus the initial "<strong>"
url=${url%</strong>} # Remove the trailing "</strong>"
如果您正在使用bash
(或具有类似功能的其他shell),则可以将扩展模式匹配与参数替换相结合。 (我不知道busybox支持哪些功能。)
# Turn on extended pattern support
shopt -s extglob
# ?(\/) matches an optional forward slash; like /? in a regex
# Expand $line, but remove all occurrances of <strong> or </strong>
# from the expansion
url=${line//<?(\/)strong>}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.