Как ввести регулярное выражение в 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
Я тоже пробовал это (но похоже, что я использую неправильный синтаксис regex):
line2 = line.replace('<[*> ', '')
line = line2.replace('</[*> ', '')
line2 = line.replace('<[*>', '')
line = line2.replace('</[*>', '')
Я не хочу жестко закодировать replace
от 1 до 99.,.
Ответы
Ответ 1
Этот проверенный фрагмент должен сделать это:
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)
Regexes - это весело! Но я бы настоятельно рекомендовал потратить час или два на изучение основ. Для начала вам нужно узнать, какие символы являются особенными: "метасимволы", которые необходимо экранировать (т.е. С обратным слэшем, расположенным спереди), и правила различаются внутри и вне классов символов.) Отличное онлайн-руководство: a href= "http://www.regular-expressions.info/" rel= "noreferrer" > www.regular-expressions.info. Время, которое вы там проводите, будет многократно платить за себя. Счастливое регулярное выражение!
Ответ 2
str.replace()
фиксированные замены. Вместо этого используйте re.sub()
.
Ответ 3
Я бы пошел так (регулярное выражение объясняется в комментариях):
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)
Если вы хотите узнать больше о регулярных выражениях, я рекомендую прочитать " Поваренную книгу регулярных выражений" Яна Гойваэрта и Стивена Левитана.
Ответ 4
Самый простой способ
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
Ответ 5
Метод replace для строковых объектов не принимает регулярные выражения, а только фиксированные строки (см. документацию: http://docs.python.org/2/library/stdtypes.html#str.replace).
Вы должны использовать re
модуль:
import re
newline= re.sub("<\/?\[[0-9]+>", "", line)
Ответ 6
не нужно использовать регулярное выражение (для вашей строки примера)
>>> 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
Ответ 7
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)