Created
July 13, 2020 20:22
-
-
Save mewforest/528fd2dd5601c25701039b94e1169213 to your computer and use it in GitHub Desktop.
Шпаргалка по основам регулярных выражений
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
# Стоит заметить, что библиотека re не поддерживает некоторые расширенные возможности регулярных выражений для Юникода. | |
# Например, для использования удобнейших групп символов, наподобии \p{Cyrillic} используйте библиотеку regex | |
# О библиотеке: https://pypi.org/project/regex/ | |
# Подробнее о дополнительном функционале: https://www.regular-expressions.info/unicode.html#prop | |
# Можно использовать match() или search() для поиска совпадений, их отличие не принципиально для случаев ниже: | |
# search ⇒ найти что-нибудь в строке и вернуть соответствующий объект. | |
# match ⇒ найти что-то в начале строки и вернуть соответствующий объект. | |
if re.match(r'hell..', 'hello'): | |
print('OK') | |
else: | |
print('NOT OK') | |
# Найти и вывести части пути | |
path = r'D:\Users\superuser\Videos\play.mp4' | |
r = re.search(r'([A-Z]):\\Users.*\.(.+)', path) | |
print(r.group(0)) # D:\Users\superuser\Videos\play.mp4 | |
print(r.group(1)) # D | |
print(r.group(2)) # mp4 | |
print(r) # <re.Match object; span=(0, 34), match='D:\\Users\\superuser\\Videos\\play.mp4'> | |
# ФИО | |
fio = re.match(r'(.*) (.).* (.).*', 'Струков Сергей Дмитриевич') | |
print('{} {}.{}.'.format(*fio.groups())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment