-
Hajipur, Bihar, 844101
RegEx stands for Regular Expression. It is a powerful tool used to search, match, and manipulate strings based on patterns.
Python provides support for regular expressions through the built-in re
module.
re
Moduleimport re
re
Function | Description |
---|---|
re.search() |
Searches for a match anywhere in string |
re.match() |
Checks for a match only at the beginning |
re.findall() |
Returns all matches in a list |
re.sub() |
Replaces matches with another string |
re.split() |
Splits string by pattern |
import re
txt = "I love Python"
result = re.search("Python", txt)
if result:
print("Match found!")
txt = "apple, banana, apple, mango"
matches = re.findall("apple", txt)
print(matches) # ['apple', 'apple']
txt = "Python is fun"
match = re.match("Python", txt)
if match:
print("Yes, it starts with Python")
txt = "I like Java"
updated = re.sub("Java", "Python", txt)
print(updated) # I like Python
txt = "one, two, three"
parts = re.split(", ", txt)
print(parts) # ['one', 'two', 'three']
Symbol | Meaning |
---|---|
. |
Any character (except newline) |
^ |
Starts with |
$ |
Ends with |
* |
Zero or more |
+ |
One or more |
? |
Zero or one |
[] |
Set of characters |
\ |
Escape character |
{} |
Specific number of occurrences |
` | ` |
() |
Group |
Use raw strings (r""
) to avoid escaping characters like \
.
pattern = r"\d+" # Matches one or more digits
Q1. Write a Python program to use re.search()
to find the word "apple"
in a sentence.
Q2. Write a Python program to use re.match()
to check if a string starts with "Hello"
.
Q3. Write a Python program to use re.findall()
to count how many times the word "dog"
appears in a sentence.
Q4. Write a Python program to replace all numbers in a string with the "#"
symbol using re.sub()
.
Q5. Write a Python program to split a string using a comma and space ", "
as the separator using re.split()
.
Q6. Write a Python program to create a regex pattern to find all email addresses in a string.
Q7. Write a Python program to match all words starting with a capital letter using regex.
Q8. Write a Python program to use ^
and $
to check if a string starts and ends with specific words.
Q9. Write a Python program to match all 3-digit numbers from a string using a regex pattern like \b\d{3}\b
.
Q10. Write a Python program to extract all words from a sentence using \w+
.
Q1: What does RegEx stand for?
Q2: Which module provides regex support in Python?
Q3: Which function checks for a match anywhere in the string?
Q4: What does \d represent in regex?
Q5: What is the output of re.findall("a", "banana")?
Q6: What symbol matches any character except newline?
Q7: What is the purpose of re.sub()?
Q8: Which regex pattern matches one or more characters?
Q9: Which method is used to split a string using regex?
Q10: What does [] do in regex?