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


317

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

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

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

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

我不想replace从1到99 进行硬编码。。。


4
接受的答案已经涵盖了您的问题并已解决。你还需要什么别的吗 ?
HamZa 2013年

结果应该是什么where the<[99> number ranges from 1-100</[100>
utapyngo 2013年

它也应该删除<...>标签中的数字,所以输出应该是where the number rangers from 1-100 ?
alvas 2013年

Answers:


565

这个经过测试的代码段应该做到这一点:

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)

正则表达式是 有趣!但我强烈建议您花一两个小时来学习基础知识。对于初学者,您需要学习哪些特殊字符:需要转义的“元字符”(即,前面加反斜杠-字符类的内外规则都不同。)在以下位置有一个出色的在线教程:www .regular-expressions.info。您在那里度过的时间将使自己获得很多回报。祝您满意!


是的,它有效!!谢谢,但是您能简要解释一下正则表达式吗?
alvas 2011年

9
也不要忽视Jeffrey Friedl
撰写

另一个很好的参考看到w3schools.com/python/python_regex.asp
卡森


23

我会这样(正则表达式在注释中说明):

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)

如果您想了解有关正则表达式的更多信息,建议阅读 Jan Goyvaerts和Steven Levithan撰写的《表达式食谱》


2
你可以简单地使用*,而不是{0,}
哈姆扎

3
来自python docs{0,}与相同*{1,}等同于+{0,1}与相同?。最好使用*+?在可能的情况下使用,因为它们较短且更易于阅读。
winklerrr

15

最简单的方法

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

括号真的必要吗?那不是相同的正则表达式<[^>]+>吗?顺便说一句:我认为您的正则表达式会匹配太多(例如<html>
winklerrr


3

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

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

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

3
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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.