One or More Pattern Matching with the Plus
While * means “match zero or more,” the + (or plus) means “match one or more.” Unlike the star, which does not require its group to appear in the matched string, the group preceding a plus must appear at least once. It is not optional. If you need to match an actual plus sign character, prefix the plus sign with a backslash to escape it: \+.
Example 1: In this example, we will match at least one occurrence of a pattern in the string.
Python3
# Python program to illustrate # matching a regular expression # with plus(+) import re batRegex = re. compile (r 'Bat(wo)+man' ) mo1 = batRegex.search( 'The Adventures of Batwoman' ) print (mo1.group()) |
Output:
Batwoman
Example 2: In this example, the regex Bat(wo)+man will not match the string ‘The Adventures of Batman’ because at least one wo is required by the plus sign.
Python
# Python program to illustrate # matching a regular expression # with plus(+) import re batRegex = re. compile (r 'Bat(wo)+man' ) mo3 = batRegex.search( 'The Adventures of Batman' ) = = None print (mo3) |
Output:
True
Related Article – Regex Cheetsheet
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.