Я думаю, что вы используете Express Edition
Попробуйте добавить «\ SQLEXPRESS» к имени вашего сервера
, например. «MY-SERVER \ SQLEXPRESS»
Этот проверенный фрагмент должен сделать это:
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)
Регулярные выражения fun! Но я бы настоятельно рекомендовал потратить час или два на изучение основ. Для начала вам нужно узнать, какие символы являются особенными: «метасимволы» , которые должны быть экранированы (т. Е. С обратным слэшем, расположенным спереди), и правила различаются внутри и вне классов символов.) отличный онлайн-учебник по адресу: www.regular-expressions.info . Время, которое вы там проводите, будет многократно платить за себя. Happy regexing!
Самый простой способ
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
17 August 2017 в 14:12
str.replace()
фиксирует замены. Вместо этого используйте re.sub()
.
не нужно использовать регулярное выражение (для вашей строки примера)
>>> 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
Я хотел бы сделать это (пояснение в комментариях):
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)
Если вы хотите узнать больше о регулярном выражении, я рекомендую прочитать Cookbook по регулярным выражениям Ян Гойваертс и Стивен Левитан.
{0,}
совпадает с *
, {1,}
эквивалентно +
, а {0,1}
совпадает с ?
. Лучше использовать *
, +
или ?
, когда можете, просто потому, что они короче и легче читать.
– winklerrr
17 August 2017 в 14:07
заменить метод строковых объектов не принимает регулярные выражения, а только фиксированные строки (см. документацию: http://docs.python.org/2/library/stdtypes.html#str.replace ) .
Вы должны использовать модуль re
:
import re
newline= re.sub("<\/?\[[0-9]+>", "", line)