Optional Operator or question mark (?) in Regular Expression
Sometimes there is a pattern that you want to match only optionally. That is, the regex should find a match whether or not that bit of text is there. The “?” character flags the group that precedes it as an optional part of the pattern.
Example 1: Here, we will search for a pattern with a pattern ‘Batman’ or ‘Batwoman’. The (wo)? part of the regular expression means that the pattern wo is an optional group. The regex will match text that has zero instances or one instance of wo in it. This is why the regex matches both ‘Batwoman’ and ‘Batman’. You can think of the ? as saying,groups “Match zero or one of the group preceding this question mark.”
If you need to match an actual question mark character, escape it with \?.
Python3
# Python program to illustrate # optional matching # with question mark(?) import re batRegex = re. compile (r 'Bat(wo)?man' ) mo1 = batRegex.search( 'The Adventures of Batman' ) mo2 = batRegex.search( 'The Adventures of Batwoman' ) print (mo1.group()) print (mo2.group()) |
Output:
Batman
Batwoman
Pattern matching in Python with Regex
You may be familiar with searching for text by pressing ctrl-F and typing in the words you’re looking for. Regular expressions go one step further: They allow you to specify a pattern of text to search for. In this article, we will see how pattern matching in Python works with Regex.