Regex Search In Python
Regular Expressions known as regex, they are a powerful tool for searching and manipulation of text in various programming languages, applications, and operating systems.
A regex is a pattern made up of characters that define a search pattern.
By using regex we can search for specific patterns with a string or text files such as words, phrases, characters, or even patterns of characters.
Some common regex operators used in searches include:
- Characters: Match a specific character or set of characters.
- Anchors: Match the beginning or end of a line or string.
- Quantifiers: The number of times a character or set of characters should be matched should be specified.
- Alternation: Match one of several alternatives.
- Grouping: Group together parts of a pattern.
- Backreferences: Refer back to a previous match.
Code # 01
import re
s = r'f'
text = 'Failure is only possible if you give up trying.'
print(re.search(s,text))
Code Output
<re.Match object; span=(26, 27), match='f'>
*Lets see what is present in index no (26 to 27)import re
s = r'f'
text = 'Failure is only possible if you give up trying.'
print(re.search(s,text))
print(text[26:27])
Code Output
fCode # 02
import res = r'fail'
text = 'Failure is only possible if you give up trying.'
print(re.search(s,text))
Code Output
None
Note: This python code search fail in given text (if not find fail in text it will return None)
Code # 03
import res = r'.possible.*up'
text = 'Failure is only possible if you give up trying.'
print(re.search(s,text))
Code Output
<re.Match object; span=(15, 39), match=' possible if you give up'>
*Lets see what is present in index no (15 to 39)
Code
text = 'Failure is only possible if you give up trying.'print(text[15:39])
Code Output
possible if you give up
Code # 04
import res = r'^Failure.*possible'
text = 'Failure is only possible if you give up trying.'
print(re.search(s,text))
Code Output
<re.Match object; span=(0, 24), match='Failure is only possible'>
LIKE SHARE AND SUBSCRIBE 👇👇👇