Найти - Пользователи
Полная версия: Пара вопросов по re.sub() и регулярным выражениям.
Начало » Python для новичков » Пара вопросов по re.sub() и регулярным выражениям.
1
MikaMika
Привет.
Не могу понять в чём разница между:
import re
re.sub(r'\s','','one\r\ntwo\nthree\r\nfive           5')
Результат:
onetwothreefive5
и
import re
re.sub(r'\s+','','one\r\ntwo\nthree\r\nfive           5')
Результат:
onetwothreefive5
В чём разница между \s и \s+

И второй вопрос.
Можно ли заменить инструкцию (которую я сейчас использую):
re.sub(r'\r\n|\r|\n| ', '', 'one\r\ntwo\nthree\r\nfive           5')
одним из предложенных выше вариантов (с “\s” или “\s+”).
Ведь они делаю одно и тоже.
reclosedev
Ответы на все есть в документации
http://docs.python.org/2/library/re.html
'+'
Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.


\s
When the UNICODE flag is not specified, it matches any whitespace character,
this is equivalent to the set [ \t\n\r\f\v].
The LOCALE flag has no extra effect on matching of the space.
If UNICODE is set, this will match the characters [ \t\n\r\f\v]
plus whatever is classified as space in the Unicode character properties database.
py.user.next
MikaMika
В чём разница между \s и \s+
\s - это один символ
\s+ - это группа символов

документация посвежее
http://docs.python.org/3/library/re.html

MikaMika
Результат:
onetwothreefive5
результат один, но процесс его достижения различается

либо она удалит один символ, заменит его на пустоту, удалит один символ, заменит его на пустоту, …

либо она удалит группу символов, заменит её на пустоту, удалит группу символов, заменит её на пустоту, …

количество замен различается

MikaMika
Можно ли заменить инструкцию (которую я сейчас использую):
это не одно и то же
MikaMika
r'\r\n|\r|\n| '
r'[\r\n ]+'
MikaMika
reclosedev, спасибо, прочитал в силу моего английского.
py.user.next, большое спасибо за развёрнутый ответ!
MikaMika
Это эквивалент \s+
r'[\r\n ]+'
, а почему в документации Python, указано, что:
\s -
When the UNICODE flag is not specified, it matches any whitespace character, this is equivalent to the set . The LOCALE flag has no extra effect on matching of the space. If UNICODE is set, this will match the characters plus whatever is classified as space in the Unicode character properties database.
Получается, что \s+ - это:
r'[ \t\n\r\f\v]+'
Получается, что, например, \s - это всё же эквивалент:
re.sub(r'\r\n|\r|\n| ', '', 'one\r\ntwo\nthree\r\nfive           5')
Все символы из этого выражения (и даже больше) входят в \s
Или я что то непонимаю?
py.user.next
MikaMika
Это эквивалент \s+
r'[\r\n ]+'
это не эквивалент \s+, это упрощённая запись твоего регулярного выражения

MikaMika
\s - When the UNICODE flag is not specified, it matches any whitespace character, this is equivalent to the set . The LOCALE flag has no extra effect on matching of the space. If UNICODE is set, this will match the characters plus whatever is classified as space in the Unicode character properties database.
в третьем питоне это давно уже работает по-другому: флаг re.UNICODE устарел, переход выполняется с помощью re.ASCII

MikaMika
Получается, что, например, \s - это всё же эквивалент:
нет, она прихватит ещё и табуляции, которых нет в исходном регулярном выражении
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB