python - 如何在 string.replace 中输入正则表达式?

标签 python regex string replace

我需要一些关于声明正则表达式的帮助。我的输入如下:

this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>

需要的输出是:

this is a paragraph with in between and then there are cases ... where the number ranges from 1-100. 
and there are many other lines in the txt files
with such tags

我试过了:

#!/usr/bin/python
import os, sys, re, glob
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
    for line in reader: 
        line2 = line.replace('<[1> ', '')
        line = line2.replace('</[1> ', '')
        line2 = line.replace('<[1>', '')
        line = line2.replace('</[1>', '')
        
        print line

我也试过这个(但似乎我使用了错误的正则表达式语法):

        line2 = line.replace('<[*> ', '')
        line = line2.replace('</[*> ', '')
        line2 = line.replace('<[*>', '')
        line = line2.replace('</[*>', '')

我不想将 replace 从 1 硬编码为 99。

最佳答案

这个经过测试的片段应该可以做到:

import re
line = re.sub(r"</?\[\d+>", "", line)

编辑:这是一个解释其工作原理的注释版本:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

正则表达式很有趣!但我强烈建议花一两个小时学习基础知识。对于初学者,您需要了解哪些字符是特殊的:"metacharacters" 需要转义(即在前面放置一个反斜杠 - 并且在字符类内部和外部的规则不同。)有优秀的在线教程:www.regular-expressions.info .你在那里度过的时间会多倍地收回成本。快乐的正则表达式!

关于python - 如何在 string.replace 中输入正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5658369/

相关文章:

python - PyCharm 和调试私有(private)属性

python - TensorFlow:使用不同的损失函数恢复训练

正则表达式删除包含确切数量分号的行,Notepad++

java - 导入包时应该使用完全限定吗?它会引起任何副作用吗?

python - 从不同目录导入 python 文件时出现 I/O 错误 :Cannot open resource,

regex - 在学习正则表达式时混合字符串解析可以吗?

python - 从替换映射递归替换

c# - String.Format 函数不起作用

c# - Python在C#中的unpack函数

python - 如何获取 QFileSystemModel 和 QTreeView 中的选定项目