ironknee 2022-04-22 11:32 采纳率: 100%
浏览 28
已结题

正则表达式re.sub替换疑惑

问题相关代码,请勿粘贴截图
import re

article = '''
<a href="http://www.test-test.com">http://www.snowwo-fasngoagn.com</a>
http://www.test-test.com
http://www.test-test.com/gsldno-sd/test'''

ss = re.sub(r'http://[a-z0-9/.-]*|https://[a-z0-9/.-]*', "", article, re.I)
print(ss)
print()
match = re.findall(r'http://[a-z0-9/.-]*|https://[a-z0-9/.-]*', article)
print(match)
运行结果及报错内容

https://ask.csdn.net/new
http://www.test-test.com/
http://www.test-test.com/gsldno-sd/test

['http://www.test-test.com', 'http://www.snowwo-fasngoagn.com', 'http://www.test-test.com', 'http://www.test-test.com/gsldno-sd/test']

我想要达到的结果

我想要用正则替换所有链接,re.findall可以匹配出来所有链接,但是re.sub只替换了部分

  • 写回答

2条回答 默认 最新

  • llc的足迹 2022-04-22 15:51
    关注

    count参数默认是0,需要指定为4,或者使用subn,不需要指定count,默认全部替换

    def sub(pattern, repl, string, count=0, flags=0):
        """Return the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in string by the
        replacement repl.  repl can be either a string or a callable;
        if a string, backslash escapes in it are processed.  If it is
        a callable, it's passed the Match object and must return
        a replacement string to be used."""
        return _compile(pattern, flags).sub(repl, string, count)
    
    def subn(pattern, repl, string, count=0, flags=0):
        """Return a 2-tuple containing (new_string, number).
        new_string is the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in the source
        string by the replacement repl.  number is the number of
        substitutions that were made. repl can be either a string or a
        callable; if a string, backslash escapes in it are processed.
        If it is a callable, it's passed the Match object and must
        return a replacement string to be used."""
        return _compile(pattern, flags).subn(repl, string, count)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 4月30日
  • 已采纳回答 4月22日
  • 创建了问题 4月22日