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 count matches with Python regex?
- How to use word boundaries in Python Regex?
- How to match the beginning of a line with Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match whitespace in Python regex?
- How to match a year with Python Regex?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
- How to split using Python regex?
- Python regex example
See more codes...