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

How to input a regex in string.replace?

我需要一些关于声明regex的帮助。我的输入如下:

1
2
3
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>

所需输出为:

1
2
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

我试过了:

1
2
3
4
5
6
7
8
9
10
#!/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

我也尝试过这个方法(但似乎我使用了错误的regex语法):

1
2
3
4
    line2 = line.replace('<[*> ', '')
    line = line2.replace('</[*> ', '')
    line2 = line.replace('<[*>', '')
    line = line2.replace('</[*>', '')

我不想硬编码从1到99的replace。…


这个测试片段应该做到:

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

编辑:这里有一个注释版本解释它的工作原理:

1
2
3
4
5
6
7
8
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)

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


str.replace()进行固定替换。用re.sub()代替。


我想要这个(Regex在评论中解释):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import re

# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")

# <\/{0,}\[\d+>
#
# Match the character"<" literally ?<?
# Match the character"/" literally ?\/{0,}?
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) ?{0,}?
# Match the character"[" literally ?\[?
# Match a single digit 0..9 ?\d+?
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) ?+?
# Match the character">" literally ?>?

subject ="""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>"""


result = pattern.sub("", subject)

print(result)

如果你想了解更多关于Regex的知识,我建议你读一下JanGoyvaerts和StevenLevithan的正则表达式食谱。


最简单的方法

1
2
3
4
5
6
import re

txt='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>'

out = re.sub("(<[^>]+>)", '', txt)
print out


字符串对象的replace方法不接受正则表达式,只接受固定字符串(请参阅文档:http://docs.python.org/2/library/stdtype.html_str.replace)。

您必须使用re模块:

1
2
import re
newline= re.sub("<\/?\[[0-9]+>","", line)


不必使用正则表达式(用于示例字符串)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> s
'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>
'


>>> for w in s.split(">"):
...   if"<" in w:
...      print w.split("<")[0]
...
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


1
2
3
4
5
6
7
8
9
10
import os, sys, re, glob

pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern ="<[1>"

for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
   for line in reader:
      retline =  pattern.sub(replacementStringMatchesPattern,"", line)        
      sys.stdout.write(retline)
      print (retline)