Opening Hours :7AM to 9PM
import re
import re def myfun(): #Check if the string starts with "The" and ends with "Germany": txt = "The rain in Germany" x = re.search("^The.*Germany$", txt) if x: print("YES! We have a match!") else: print("No match") if __name__=="__main__": myfun()
Function | Description |
---|---|
findall | Returns a list containing all matches |
search | Returns a Match object if there is a match anywhere in the string |
split | Returns a list where the string has been split at each match |
sub | Replaces one or many matches with a string |
import re def myfun(): #Return a list containing every occurrence of "ni": txt = "The raining in Germani" x = re.findall("ni", txt) print(x) if __name__=="__main__": myfun()The list contains the matches in the order they are found.
import re def myfun(): #Return a list containing every occurrence of "pi": txt = "The raining in Germani" x = re.findall("pi", txt) print(x) if __name__=="__main__": myfun()
import re def myfun(): txt = "The rain in Germany" x = re.search("\s", txt) print("The first white-space character is located in position:", x.start()) if __name__=="__main__": myfun()If no matches are found, the value None is returned:
import re def myfun(): txt = "The rain in Germany" x = re.search("sateesh", txt) print(x) if __name__=="__main__": myfun()
import re def myfun(): #Split the string at every white-space character: txt = "The rain in Germany" x = re.split("\s", txt) print(x) if __name__=="__main__": myfun()You can control the number of occurrences by specifying the maxsplit parameter:
import re def myfun(): #Split the string at the first white-space character: txt = "The rain in Spain" x = re.split("\s", txt, 1) print(x) if __name__=="__main__": myfun()
import re def myfun(): #Replace all white-space characters with the digit "24": txt = "The rain in Spain" x = re.sub("\s", "24", txt) print(x) if __name__=="__main__": myfun()
import re def myfun(): #Replace the first two occurrences of a white-space character with the digit 24: txt = "The rain in Germany" x = re.sub("\s", "24", txt, 2) print(x) if __name__=="__main__": myfun()