Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python re.fullmatch() method



The Python re.fullmatch() method is used to check if the entire string matches a given regular expression pattern.

Unlike re.match() method which only matches from the start of the string whereas re.fullmatch() method ensures the pattern spans the entire string. If the pattern matches completely it returns a match object otherwise it returns None.

This method is useful when we need to validate that a string fully conforms to a specific format.

Syntax

Following is the syntax and parameters of Python re.fullmatch() method −

re.fullmatch(pattern, string, flags=0)

Parameters

Following are the parameter of the python re.fullmatch() method −

  • pattern: The regular expression pattern to match.
  • string: The string to be matched against the pattern.
  • flags(optional): These flags modify the matching behavior

Return value

This method returns the match object if the pattern is found in the string otherwise it returns None.

Example 1

Following is the basic example of using the re.fullmatch() method. In this example the pattern '\d+' matches one or more digits which fully matches the entire string '123456' −

import re

result = re.fullmatch(r'\d+', '123456')
if result:
    print("Full match found:", result.group())  

Output

Full match found: 123456

Example 2

Here in this example the pattern '\w+' matches one or more alphanumeric characters which fully matches the string 'abc123' −

import re
result = re.fullmatch(r'\w+', 'abc123')
if result:
    print("Full match found:", result.group())  

Output

Full match found: abc123

Example 3

Here in this example we use the re.IGNORECASE flag for making the pattern case-insensitive allowing 'hello' to fully match with 'HELLO' −

import re

result = re.fullmatch(r'hello', 'HELLO', re.IGNORECASE)
if result:
    print("Full match found:", result.group()) 

Output

Full match found: HELLO

Example 4

The below example checks whether the string is fully matched or not −

import re

result = re.fullmatch(r'\d+', '123abc')
if result:
    print("Full match found:", result.group())
else:
    print("No full match found")  

Output

No full match found
python_modules.htm
Advertisements