Форум сайта python.su
0
Привет.
Не могу понять в чём разница между:
import re re.sub(r'\s','','one\r\ntwo\nthree\r\nfive 5')
import re re.sub(r'\s+','','one\r\ntwo\nthree\r\nfive 5')
re.sub(r'\r\n|\r|\n| ', '', 'one\r\ntwo\nthree\r\nfive 5')
Отредактировано MikaMika (Июнь 11, 2013 15:14:03)
Офлайн
173
Ответы на все есть в документации
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.
Офлайн
857
MikaMika\s - это один символ
В чём разница между \s и \s+
MikaMikaрезультат один, но процесс его достижения различается
Результат:
onetwothreefive5
MikaMikaэто не одно и то же
Можно ли заменить инструкцию (которую я сейчас использую):
MikaMikar'\r\n|\r|\n| '
r'[\r\n ]+'
Офлайн
0
reclosedev, спасибо, прочитал в силу моего английского.
py.user.next, большое спасибо за развёрнутый ответ!
Офлайн
0
Это эквивалент \s+
r'[\r\n ]+'
r'[ \t\n\r\f\v]+'
re.sub(r'\r\n|\r|\n| ', '', 'one\r\ntwo\nthree\r\nfive 5')
Отредактировано MikaMika (Июнь 12, 2013 12:51:16)
Офлайн
857
MikaMikaэто не эквивалент \s+, это упрощённая запись твоего регулярного выражения
Это эквивалент \s+r'[\r\n ]+'
MikaMikaв третьем питоне это давно уже работает по-другому: флаг re.UNICODE устарел, переход выполняется с помощью re.ASCII
\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.
MikaMikaнет, она прихватит ещё и табуляции, которых нет в исходном регулярном выражении
Получается, что, например, \s - это всё же эквивалент:
Офлайн