Zero or More Pattern Matching with the Star
The * (called the star or asterisk) means “match zero or more” — the group that precedes the star can occur any number of times in the text. It can be completely absent or repeated over and over again. If you need to match an actual star character, prefix the star in the regular expression with a backslash, \*.
Example 1: In this example, we will match the zero occurrences of a pattern in the string. The (wo)* part of the regex matches zero instances of wo in the string.
Python3
# Python program to illustrate # matching a regular expression # with asterisk(*) import re batRegex = re. compile (r 'Bat(wo)*man' ) mo1 = batRegex.search( 'The Adventures of Batman' ) print (mo1.group()) |
Output:
Batman
Example 2: In this example, we will match at least one occurrence of a pattern in the string.
Python
#python program to illustrate #matching a regular expression #with asterisk(*) import re batRegex = re. compile (r 'Bat(wo)*man' ) mo2 = batRegex.search( 'The Adventures of Batwoman' ) print (mo2.group()) |
Output:
Batwoman
Example 3: In this example, we will match more than one occurrence of a pattern in the string.
Python
# Python program to illustrate # matching a regular expression # with asterisk(*) import re batRegex = re. compile (r 'Bat(wo)*man' ) mo3 = batRegex.search( 'The Adventures of Batwowowowoman' ) print (mo3.group()) |
Output:
Batwowowowoman
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.