9951 explained code solutions for 126 technologies


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

Edit this code on GitHub