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 plus sign in Python regex?
- How to match whitespace in Python regex?
- How to replace in a file using Python regex?
- How to match a question mark in Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a hex number with regex in Python?
- How to quote in Python regex?
- How to match a year with Python Regex?
- How to match a UUID using Python regex?
- How to remove numbers from a string using Python regex?
See more codes...