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 match a question mark in Python regex?
- How to match a UUID using Python regex?
- How to ignore case in Python regex?
- How to get a group from a regex in Python?
- How to find all matches with regex in Python?
- How to do an exact match with regex in Python?
- How to regex match excluding a word in Python?
- How to count matches with Python regex?
- How to remove special characters using Python regex?
- How to replace using Python regex?
See more codes...