python-regexHow to match zero or one occurence in Python regex?
To match zero or one occurence in Python regex, the ?
operator can be used.
For example,
import re
string = "Hello World"
match = re.search(r"World?", string)
if match:
print("Match found:", match.group())
else:
print("No match")
Output example
Match found: World
The ?
operator is used to match zero or one occurence of the preceding character or group. In the example above, the ?
operator is used to match zero or one occurence of the string World
.
Code explanation
?
operator: used to match zero or one occurence of the preceding character or group
Helpful links
More of Python Regex
- How to use quantifiers in Python regex?
- How to match a year with Python Regex?
- How to make a case insensitive match with Python regex?
- How to regex match excluding a word in Python?
- How to regex match excluding a character in Python?
- How to match a plus sign in Python regex?
- How to match one or more occurence in Python regex?
- How to perform a zero length match with Python Regex?
- How to replace a certain group using Python regex?
See more codes...