python-regexHow to match a plus sign in Python regex?
To match a plus sign in Python regex, use the +
character. This character will match one or more of the preceding character. For example, the following code will match any string that contains one or more a
characters:
import re
pattern = re.compile(r'a+')
string = 'aaabbbccc'
match = pattern.search(string)
if match:
print(match.group())
Output example
aaa
The code consists of the following parts:
import re
- imports there
module which provides regular expression matching operations.pattern = re.compile(r'a+')
- creates a regular expression pattern object with the patterna+
which will match one or morea
characters.string = 'aaabbbccc'
- creates a string to match against.match = pattern.search(string)
- searches the string for a match against the pattern.if match:
- checks if a match was found.print(match.group())
- prints the matched string.
Helpful links
More of Python Regex
- How to match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to get all matches from a regex in Python?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to match a hex number with regex in Python?
- How to match a YYYY-MM-DD date with Python Regex?
- How to get a group from a regex in Python?
- How to match a UUID using Python regex?
- How to remove numbers from a string using Python regex?
See more codes...