Python 3.x 字符串替换:多行,不区分大小写,带特殊字符

Python 3.x 字符串替换:多行,不区分大小写,带特殊字符,python-3.x,string,re,Python 3.x,String,Re,目标:给定一个字符串,用空字符串替换所有出现的和大写的近亲 一个string.replace解决方案和/或一个re.sub解决方案会很好。基于BeautifulSoup模块的解决方案将被视为最后手段 基于字符串的尝试。替换: 问题:根本不起作用。然而,一个更简单的例子是可行的: import re s = '1:a\n2:A' ## 1:a ## 2:A h = 'a' r = re.sub(h, '', s, flags=re.IGNORECAS

目标:给定一个字符串,用空字符串替换所有出现的和大写的近亲

一个string.replace解决方案和/或一个re.sub解决方案会很好。基于BeautifulSoup模块的解决方案将被视为最后手段

基于字符串的尝试。替换:

问题:根本不起作用。然而,一个更简单的例子是可行的:

    import re
    s = '1:a\n2:A'
    ## 1:a
    ## 2:A
    h = 'a'
    r = re.sub(h, '', s, flags=re.IGNORECASE | re.MULTILINE)
    ## 1:
    ## 2:
我怀疑问题来自字符串中的特殊字符,例如是,是吗?和是正则表达式的特殊字符。您可以使用例如re.escape:


没有解决我的问题的引用:,是否存在需要re.MULTILINE的情况?不知道文档在说什么:当指定此标志时,^在字符串开头和字符串中每行的开头匹配,紧跟在每一换行之后。类似地,$metacharacter在字符串末尾和紧靠换行符前面的每行末尾匹配@PatrickT是的,如果要匹配行的开始/结束,需要使用re.M。例如:and-带有re.M的示例匹配所有行,没有re.M的示例只匹配最后一行。非常感谢Andrej!再过6分钟我就可以对你的答案投赞成票了-
import re
s = '1:<?xml version="1.0" encoding="utf-8"?>\n2:<?xml version="1.0" encoding="UTF-8"?>'
## 1:<?xml version="1.0" encoding="utf-8"?>
## 2:<?xml version="1.0" encoding="UTF-8"?>
h = '<?xml version="1.0" encoding="utf-8"?>'
r = re.sub(h, '', s, flags=re.IGNORECASE | re.MULTILINE)
## 1:<?xml version="1.0" encoding="utf-8"?>
## 2:<?xml version="1.0" encoding="UTF-8"?>
    import re
    s = '1:a\n2:A'
    ## 1:a
    ## 2:A
    h = 'a'
    r = re.sub(h, '', s, flags=re.IGNORECASE | re.MULTILINE)
    ## 1:
    ## 2:
import re
s = '1:<?xml version="1.0" encoding="utf-8"?>\n2:<?xml version="1.0" encoding="UTF-8"?>'
h = re.escape('<?xml version="1.0" encoding="utf-8"?>') # <-- put re.escape() around the string
r = re.sub(h, '', s, flags=re.IGNORECASE)               # <-- no need for RE.MULTILINE

print(r)
1:
2: