import re
my_string="Your birth day is on 24-12-2002"
dt=re.search("([0-9]{2}\-[0-9]{2}\-[0-9]{4})", my_string)
print(dt[1])
Output is here
24-12-2002
import re
path='C:/dir_name/string_functions.php' # path of the file to read
fob=open(path,'r') # Open in read mode
data=fob.read() # collect data
fob.close() # close file object
#print(data)
urls1 = re.findall(r'href=[\'"]?([^\'" >]+)', data)
print(urls1)
For case insensitive search use this.
urls1 = re.findall(r'href=[\'"]?([^\'" >]+)', data,re.IGNORECASE)
import re
if re.search('PLUS', 'Welcome to plus2net.com', re.IGNORECASE):
print('It is there') # True
else:
print('It is NOT there') # False
Output is
It is there
find(): searching string
We can use regular expressions to identify and extract email addresses from a string. This is useful for tasks like data cleaning or web scraping.
import re
text = "Contact us at support@example.com or sales@example.co.uk"
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b', text)
print(emails)
['support@example.com', 'sales@example.co.uk']
We can enhance the user experience by implementing regular expressions to validate the complexity of user-entered passwords.
import re
password = "P@ssw0rd123"
if re.match(r'^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@#$%^&+=]).{8,}$', password):
print("Password is strong")
else:
print("Password is weak")
Password is strong
The re.sub() method allows us to search for patterns and replace them. This is beneficial when sanitizing or formatting text.
import re
text = "Visit https://www.example.com or http://example.org"
updated_text = re.sub(r'https?://\S+', '[LINK]', text)
print(updated_text)
Visit [LINK] or [LINK]
Regular expressions can be used to split a string based on multiple delimiters. This is useful for parsing CSV-like strings.
import re
data = "apple;banana,orange:grape"
fruits = re.split(r'[;,:]', data)
print(fruits)
Output
['apple', 'banana', 'orange', 'grape']
All String methods