【问题标题】:Replace underscore from all html href with regex and python用正则表达式和python替换所有html href中的下划线
【发布时间】:2021-11-03 20:50:37
【问题描述】:

所以我目前正在使用python。

如何浏览 HTML 文件并替换所有出现的:

<a href="#some_snake_case_text">

并将其转换为:

<a href="#somesnakecasetext">

href里面有独立的文字吗?

所以我打算使用正则表达式,我现在已经使用了几个小时,但我没有成功匹配 href 标记之间的“_”以删除它们。 .. 我不能只匹配这个词并替换所有 cus,这实际上会替换整个文档中的所有内容,这不是预期的。

我试着用这个来计算所有的“_”

<a href=\"#(.*(_).*)+\">

或除下划线以外的所有内容:

<a href=\"#([^_]_?)+\">

然后也许替换它?!

我该怎么做?

【问题讨论】:

  • 还请在下面为有用的答案投票,谢谢。

标签: python regex


【解决方案1】:

你可以使用re.sub:

import re
s = '<a href="#some_snake_case_text">'
new_s = re.sub('(?<=href\=")[^"]+', lambda x:''.join(x.group().split('_')), s)

输出:

'<a href="#somesnakecasetext">'

【讨论】:

    【解决方案2】:

    使用替换方法:

    import re
    
    def subst(x):
        return x.group().replace('_', '')
    
    s = 'xxx <a href="#some_snake_case_text"> xxx'
    p = r'<a\s+href="#[^"]*">'
    print(re.sub(p, subst, s))
    

    Python proof.

    结果xxx &lt;a href="#somesnakecasetext"&gt; xxx

    解释

    --------------------------------------------------------------------------------
      <a                       '<a'
    --------------------------------------------------------------------------------
      \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                               more times (matching the most amount
                               possible))
    --------------------------------------------------------------------------------
      href="#                  'href="#'
    --------------------------------------------------------------------------------
      [^"]*                    any character except: '"' (0 or more times
                               (matching the most amount possible))
    --------------------------------------------------------------------------------
      ">                       '">'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多