re 에 관해서

Leejaegun·2025년 3월 30일

코딩테스트 시리즈

목록 보기
35/49

🧠 Python re Module — Summary

🔧 Commonly Used Methods:

MethodDescriptionExample
re.search()Finds the first match anywhere in the stringre.search(r'\d+', 'abc123') → '123'
re.match()Matches a pattern only at the beginningre.match(r'\d+', '123abc') → '123'
re.findall()Returns all non-overlapping matches as a listre.findall(r'\d+', 'a1b22') → ['1', '22']
re.sub()Replaces matched substringsre.sub(r'\d+', '*', 'abc123') → 'abc*'
re.split()Splits string based on regex patternre.split(r'[\s,]+', 'a, b c') → ['a', 'b', 'c']

Use r'...' to write regex in Python so that backslashes like \s are treated literally, not as Python escape characters. ✅

📘 Regex Pattern Cheatsheet:

PatternMeaningExample Match
\dDigit (0–9)'1', '5'
\DNon-digit'a', '#'
\wWord character (a-z, A-Z, 0–9, _)'a', 'Z', '7'
\WNon-word character'@', ' '
\sWhitespace (space, tab, newline)' ', '\n', '\t'
\SNon-whitespace'a', '1', '.'
.Any character (except newline)'a', '5', '!'
*0 or more times'a*''', 'aaa'
+1 or more times'a+''a', 'aa'
{m,n}Between m and n times'a{2,4}''aa'
``OR
()Grouping(\d+)-(\w+)
[]Character set[a-z], [0-9]

✅ Examples we've used:

command = "G()(al)"

1. Replace () with "o" and (al) with "al":

re.sub(r'\(\)', 'o', re.sub(r'\(al\)', 'al', command))

2. Extract all numbers:

re.findall(r'\d+', 'I have 2 apples and 10 bananas')  # ['2', '10']

3. Replace multiple spaces with one:

re.sub(r'\s+', ' ', 'This   is  ChatGPT')  # 'This is ChatGPT'

4. Split by space, comma, or semicolon:

re.split(r'[,\s;]+', 'apple, banana; orange')  # ['apple', 'banana', 'orange']

🧪 Example 1: Check if a string is a valid email

import re

email = "test123@example.com"
if re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):
    print("✅ Valid email")
else:
    print("❌ Invalid email")

🧪 Example 2: Extract all words that start with a capital letter

text = "Alice and Bob went to NewYork"
capital_words = re.findall(r'\b[A-Z][a-z]*\b', text)
print(capital_words)  # ['Alice', 'Bob', 'NewYork']

🧪 Example 3: Replace all digits with #

text = "My phone number is 010-1234-5678"
masked = re.sub(r'\d', '#', text)
print(masked)  # "My phone number is ###-####-####"

🧪 Example 4: Extract hashtags from a sentence

text = "Today is great! #sunny #happy #blessed"
hashtags = re.findall(r'#\w+', text)
print(hashtags)  # ['#sunny', '#happy', '#blessed']

🧪 Example 5: Remove HTML tags

html = "<div>Hello <b>world</b></div>"
cleaned = re.sub(r'<.*?>', '', html)
print(cleaned)  # "Hello world"
profile
Lee_AA

0개의 댓글