Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!

Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount

Регулярни изрази


Regular Expressions (понякога съкратено като regexp, regex или re) са инструмент за съвпадение на модели в текст. В Python, имаме модула re. Приложенията за регулярни изрази са широко разпространени, но те са доста сложни, затова, когато обмисляте използването на регулярен израз за определена задача, помислете за алтернативи и се обърнете към тях само като последна мярка.

Пример за регулярен израз е r"^(From|To|Cc).*[email protected]". Сега за обяснението: каретката ^ съвпада с текст в началото на реда. Следващата група, частта с (From|To|Cc) означава, че редът трябва да започва с една от думите, които са разделени с тръбата |. Това се нарича OR оператор, и регулярният израз ще съвпадне, ако редът започва с която и да е дума от групата. .*? означава неагресивно съвпадение на всякакъв брой символи, с изключение на символа за нов ред \n. Неагресивната част означава да се съвпадат възможно най-малко повторения. Символът . означава всеки символ, който не е нов ред, * означава да се повтаря 0 или повече пъти, а символът ? прави го неагресивен.

И така, следните редове ще бъдат съвпаднати от този регулярен израз: From: [email protected] To: !asp]<,. [email protected]

Пълна справка за синтаксиса на re е налична в python docs.

Като пример за "правилен" регулярен израз за съвпадение на имейл (като този в упражнението), вижте тук

# Example: import re pattern = re.compile(r"\[(on|off)\]") # Slight optimization print(re.search(pattern, "Mono: Playback 65 [75%] [-16.50dB] [on]")) # Returns a Match object! print(re.search(pattern, "Nada...:-(")) # Doesn't return anything. # End Example # Exercise: make a regular expression that will match an email def test_email(your_pattern): pattern = re.compile(your_pattern) emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"] for email in emails: if not re.match(pattern, email): print("You failed to match %s" % (email)) elif not your_pattern: print("Forgot to enter a pattern!") else: print("Pass") pattern = r"" # Your pattern here! test_email(pattern) # Exercise: make a regular expression that will match an email import re def test_email(your_pattern): pattern = re.compile(your_pattern) emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"] for email in emails: if not re.match(pattern, email): print("You failed to match %s" % (email)) elif not your_pattern: print("Forgot to enter a pattern!") else: print("Pass") # Your pattern here! pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?" test_email(pattern) test_output_contains("Pass") success_msg("Great work!")

This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy