Как ввести регулярное выражение в string.replace? - PullRequest
238 голосов
/ 14 апреля 2011

Мне нужна помощь в объявлении регулярного выражения. Мои входные данные выглядят следующим образом:

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

Ответы [ 7 ]

453 голосов
/ 14 апреля 2011

Этот проверенный фрагмент должен сделать это:

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 . Время, проведенное там, окупится много раз. Счастливое регулярное выражение!

32 голосов
/ 14 апреля 2011

str.replace() делает фиксированные замены.Вместо этого используйте re.sub().

20 голосов
/ 27 июня 2013

Я бы пошел так (регулярное выражение объяснено в комментариях):

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)

Если вы хотите больше узнать о регулярных выражениях, я рекомендую прочитать Поваренная книга регулярных выражений от Яна Гойваертса и Стивена Левитана.

13 голосов
/ 14 мая 2013

Самый простой способ

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
8 голосов
/ 16 мая 2013

метод замены строковых объектов не принимает регулярные выражения, а только фиксированные строки (см. Документацию: http://docs.python.org/2/library/stdtypes.html#str.replace).

Вы должны использовать re модуль:

import re
newline= re.sub("<\/?\[[0-9]+>", "", line)
3 голосов
/ 14 апреля 2011

не нужно использовать регулярное выражение (для вашей строки образца)

>>> 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
1 голос
/ 25 января 2019
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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...