Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

RegEx

🔍 What is RegEx?

Regular Expressions (RegEx) are patterns used to match text. Think of it as a smart search tool — you can search for things like:

  • phone numbers
  • emails
  • specific words
  • patterns in strings

🐍 Python and RegEx

Python has a built-in module called re for working with regular expressions.

import re

✅ Common Functions in re Module

FunctionDescription
re.search()Search for a pattern in a string
re.findall()Find all matches in a string
re.match()Check if the pattern matches start
re.sub()Replace a pattern with something else

📌 Example 1: Search for a word

import re

text = "Hello, my name is Sam."
result = re.search("Sam", text)

if result:
    print("Match found!")
else:
    print("No match.")

📌 Example 2: Find all digits

import re

text = "My phone number is 9876543210."
numbers = re.findall(r"\d", text)
print(numbers)  # ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0']

🧠 \d means any digit.

✨ Common RegEx Patterns

PatternMeaningExample Match
\dAny digit (0–9)“5”, “9”
\wAny letter, digit, _“abc”, “123”
\sAny whitespace (space, tab)” “
.Any character (except newline)“a”, “3”, “!”
^Start of string^Hello matches “Hello world”
$End of stringworld$ matches “Hello world”
+One or more\d+ matches “123”
*Zero or morea* matches “”, “aaa”
[]Set of characters[aeiou] matches any vowel

📌 Example 3: Replace numbers with X

import re

text = "My score is 98"
new_text = re.sub(r"\d", "X", text)
print(new_text)  # Output: My score is XX
 

    Leave a Reply

    Your email address will not be published.

    Need Help?