search() in regex in python by R4R Team

- search() is a python regex function that searches the string for a match, and returns a Match object if there is a match.

Syntax-

re.search(pattern,string)

-Here pattern is everything that you want to search in the string, metacharacters are also used in making pattern.

Example-

string is s="This is online"
then re.search("is",s)
it will search the 'is' in the given string and match will be found successfully.


program-

import re

#Check if the string starts with "This" and ends with "string":
s= "This is the amazing string"
x = re.search("^This.*string$", s)
if (x):
print("We have a match!")
else:
print("No match")


s= "The amazing string"
x = re.search("^This.*string$", s)
if (x):
print("We have a match!")
else:
print("No match")


output-

We have a match!
No match


-In this program, we have a string "This is the amazing string", and we check that string is starts with 'This' and ends with 'string'
-so "^This.*string$" shows that our required string is starts with 'This', in between every thing is acceptable, and 'string' is in the end.
- '^' shows the starting , '$' shows the ending and '.*' shows between.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!