CHAPTER 19
Regular Expressions
Regex patterns — text में search, validate, replace करना
Advertisement
Regex Basics
Regular Expressions से text में patterns ढूंढ सकते हैं।
python
import re text = "Phone: 9876543210, Email: abc@gmail.com" # search - पहला match m = re.search(r'\d{10}', text) if m: print(f"Phone: {m.group()}") # findall - सब matches nums = re.findall(r'\d+', text) print(nums) # ['9876543210'] # Email validate def is_email(email): p = r'^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$' return bool(re.match(p, email)) print(is_email("abc@gmail.com")) # True print(is_email("abc@gmail")) # False
OUTPUT
Phone: 9876543210
['9876543210']
True
FalseAdvertisement
Regex Replace
re.sub() से text में patterns को replace कर सकते हैं।
python
import re # Numbers को *** से replace text = "Card: 4111 1111 1111 1111" safe = re.sub(r'\d', '*', text) print(safe) # Card: **** **** **** **** # Extra spaces हटाना text2 = "Hello World Python" clean = re.sub(r'\s+', ' ', text2) print(clean) # Hello World Python # Split करना data = "राम,श्याम;गीता|मोहन" parts = re.split(r'[,;|]', data) print(parts)
OUTPUT
Card: **** **** **** ****
Hello World Python🎯 QUICK QUIZ — Chapter 19
Regex क्या है?
Advertisement