์ ๊ทํํ์(Regular Expression)์ด๋?
์ ๊ท ํํ์์ ๋ฌธ์์ด์์ ํน์ ํ ํจํด์ ๊ฒ์ํ๊ฑฐ๋, ๋์ฒด, ๋ถ๋ฆฌํ๋ ๋ฑ์ ์์
์ ์ํํ ๋ ์ฌ์ฉ๋๋ค. ์ด๋ฉ์ผ์ฃผ์์ฐพ๊ธฐ, ์์ด๋,๋น๋ฒ ํจํด์ฐพ๊ธฐ, ํ์๊ฐ์
์์ด๋ ํจํด ๋ฑ ์ด๋ฐ ๋ค์ํ ํจํด๋ค์ ๋ง๋ค์ด ๋ฐ์ดํฐ์์ ๋ฌธ์์ด์ ์ฐพ์๋ด๊ฑฐ๋ ๋ถ์์ ์ํํ ์ ์๋ค.
ํ์ด์ฌ์์ ์ ๊ทํํ์ ์ฌ์ฉ๋ฒ
๋จผ์ , ํจํด์ re.compile() ํจ์๋ฅผ ์ด์ฉํด ์ปดํ์ผํ๊ณ , ์ด๋ฅผ ํตํด ํจํด ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.
์ฃผ์ ํํ์
โข
^: ๋ฌธ์์ด์ ์์๊ณผ ์ผ์น
โข
$: ๋ฌธ์์ด์ ๋๊ณผ ์ผ์น
โข
\b: ๋จ์ด ๊ฒฝ๊ณ์ ์ผ์น
โข
\d: ์ซ์์ ์ผ์น
โข
\s: ๊ณต๋ฐฑ ๋ฌธ์์ ์ผ์น
โข
[abc]: a, b, c ์ค ํ๋์ ์ผ์นํ๋ ๋ฌธ์
โข
(a|b): a ๋๋ b์ ์ผ์น
โข
+, * : 0๊ฐ ์ด์ ๋๋ 1๊ฐ ์ด์์ ํจํด์ ๋ชจ๋ ์ฐพ
๋ฌธ์์ด ๊ฒ์
ํจํด์ ์์ฑํ์๋ค๋ฉด, match(), search(), findall(), finditer() ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌธ์์ด์์ ํจํด๊ณผ ์ผ์นํ๋ ๋ถ๋ถ์ ์ฐพ์ ์ ์๋ค.
โข
match() ํจ์๋ ๋ฌธ์์ด์ ์์๋ถํฐ ํจํด๊ณผ ์ผ์นํ๋์ง ๊ฒ์ฌํ๋ค.
โข
search() ํจ์๋ ๋ฌธ์์ด ์ ์ฒด์ ๊ฑธ์ณ ์ฒซ ๋ฒ์งธ๋ก ํจํด๊ณผ ์ผ์นํ๋ ๋ถ๋ถ์ ์ฐพ๋๋ค.
โข
findall() ํจ์๋ ํจํด๊ณผ ์ผ์นํ๋ ๋ชจ๋ ๋ถ๋ถ์ ์ฐพ์ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ค.
โข
finditer() ํจ์๋ ํจํด๊ณผ ์ผ์นํ๋ ๋ชจ๋ ๋ถ๋ถ์ ๋ํ ์ดํฐ๋ ์ดํฐ๋ฅผ ๋ฐํํ๋ค.
๋ฌธ์์ด ๋์ฒด
sub() ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ํจํด๊ณผ ์ผ์นํ๋ ๋ถ๋ถ์ ๋ค๋ฅธ ๋ฌธ์์ด๋ก ๋์ฒดํ ์ ์๋ค.
์ค์ต ์ฝ๋
๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
import re
# ํจํด ์ปดํ์ผ
pattern = re.compile(r'\bfoo\b')
# ๊ฒ์
search_result = pattern.search('bar foo baz') # foo์ ์ผ์นํ๋ ๋ถ๋ถ ๊ฒ์
if search_result:
print("Search found:", search_result.group())
# ๋์ฒด
replace_result = pattern.sub('bar', 'foo foo foo') # foo๋ฅผ bar๋ก ๋์ฒด
print("Replace result:", replace_result)
# ๋ชจ๋ ์ผ์น ํญ๋ชฉ ์ฐพ๊ธฐ
findall_result = pattern.findall('foo bar foo baz foo')
print("Find all result:", findall_result)
Python
๋ณต์ฌ
์ด๋ฉ์ผ ์ฐพ๊ธฐ
import re
text = "Please contact us at support@example.com for assistance."
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}'
emails = re.findall(pattern, text)
print(emails) # ['support@example.com']
Python
๋ณต์ฌ
url ์ถ์ถํ๊ธฐ
import re
text = "Visit our website at https://www.example.com or http://www.example.org"
pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
urls = re.findall(pattern, text)
print(urls) # ['https://www.example.com', 'http://www.example.org']
Python
๋ณต์ฌ
์ ํ๋ฒํธ ํ์ ํ์ธํ๊ธฐ
import re
phone_numbers = ["123-456-7890", "123 456 7890", "(123) 456-7890", "123.456.7890", "1234567890"]
pattern = r'(\(?\d{3}\)?[\s.-]?)?\d{3}[\s.-]?\d{4}'
for number in phone_numbers:
if re.match(pattern, number):
print(f"{number} is a valid phone number.")
else:
print(f"{number} is not a valid phone number.")
Python
๋ณต์ฌ
HTML ํ๊ทธ ์ ๊ฑฐ
import re
html = "<title>Example Page</title><body>Content with <b>bold</b> text.</body>"
clean_text = re.sub(r'<[^>]+>', '', html)
print(clean_text) # Example PageContent with bold text.
Python
๋ณต์ฌ