【问题标题】:Extract url from a string with regex in shell script在 shell 脚本中使用正则表达式从字符串中提取 url
【发布时间】:2012-09-11 14:19:18
【问题描述】:

我需要提取一个用<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。

【问题讨论】:

    标签: regex shell busybox


    【解决方案1】:

    这可能有效:

    url=$(echo $line | sed -r 's/<strong>([^<]+)<\/strong>/\1/')
    

    【讨论】:

      【解决方案2】:
      url=$(echo $line | sed -n 's!<strong>\(http://[^<]*\)</strong>!\1!p')
      

      【讨论】:

        【解决方案3】:

        您不必用反斜杠转义正斜杠。只有反斜杠需要在正则表达式中转义。您还应该对?-operator 使用非贪婪匹配,以避免在 HTML 源代码中有多个强标签时得到更多。

        strong>(http://.+?)</strong
        

        【讨论】:

          【解决方案4】:

          更新:由于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>}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-07-24
            • 1970-01-01
            • 1970-01-01
            • 2021-12-26
            • 2021-07-31
            • 2014-10-17
            • 2013-02-24
            相关资源
            最近更新 更多