Regex full match python

Python Regex fullmatch()

Краткое описание: в этом уроке вы узнаете, как использовать функцию Python regex fullmatch() для сопоставления всей строки с регулярным выражением.

Введение в функцию Python regex fullmatch

Функция fullmatch() возвращает объект Match , если вся строка соответствует шаблону поиска регулярного выражения, или None в противном случае.

Синтаксис функции fullmatch() следующий:

re.fullmatch(pattern, string, flags=0)
Code language: Python (python)
  • pattern задает регулярное выражение для поиска.
  • string задает входную строку.
  • Параметр flags является необязательным и по умолчанию равен нулю. Параметр flags принимает один или несколько флагов регекса. Параметр flags изменяет способ соответствия шаблона механизму regex.

Пример функции полного соответствия regex в Python

В следующем примере используется функция fullmatch() для проверки адреса электронной почты:

import re email = 'no-reply@pythontutorial.net' pattern = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]' match = re.fullmatch(pattern, email) if match is not None: print(f'The email "" is valid') else: print(f'The email """ is not valid')
Code language: Python (python)
The email "no-reply@pythontutorial.net" is valid
Code language: Python (python)

Ниже определена функция, которая использует функцию fullmatch() для проверки адреса электронной почты. Она возвращает True , если адрес электронной почты действителен, или вызывает исключение ValueError в противном случае:

import re def is_email(s: str) -> bool: pattern = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Z|a-z]' if re.fullmatch(pattern, s) is None: raise ValueError(f'The is not a valid email address') return True
Code language: Python (python)

Вы можете использовать функцию is_email() для проверки электронной почты следующим образом:

if __name__ == '__main__': try: if is_email('no-reply@pythontutorial'): print('The email is valid') except ValueError as e: print(e)
Code language: Python (python)
The no-reply@pythontutorial is not a valid email address
Code language: Python (python)

Python regex fullmatch vs match

Обе функции fullmatch() и match() возвращают объект Match , если находят совпадение.

Читайте также:  background-repeat

Функция fullmatch() сопоставляет всю строку с шаблоном, а функция match() находит совпадение только в начале строки. Смотрите следующий пример:

import re s = 'Python 3' pattern = 'Python' # fullmatch match = re.fullmatch(pattern, s) if match is not None: print('fullmatch:', match.group()) # search match = re.match(pattern, s) if match is not None: print('match:', match.group())
Code language: Python (python)
match: Python
Code language: Python (python)

В этом примере функция fullmatch() возвращает None , потому что шаблон Python соответствует только началу строки, а не всей строке.

С другой стороны, функция match() ищет шаблон в начале строки и возвращает совпадение.

Python fullmatch против поиска

Обе функции fullmatch() и search() возвращают объект Match , если находят совпадение шаблона в строке. Однако функция fullmatch() проверяет всю строку, в то время как search() проверяет любое место в строке.

import re s = 'Python 3' pattern = 'd' # fullmatch match = re.fullmatch(pattern,s) if match is not None: print(match.group()) # search match = re.search(pattern,s) if match is not None: print(match.group()) # 3
Code language: Python (python)
3
Code language: Python (python)

В этом примере шаблон d соответствует одной цифре. Функция fullmatch() возвращает None , потому что вся строка ‘Python 3’ не совпадает.

Однако функция search() возвращает совпадение, потому что она смогла найти цифру 3 в конце строки.

Резюме

  • Используйте функцию Python regex fullmatch() для проверки соответствия всей строки шаблону регулярного выражения.

Источник

Python Regex fullmatch()

Summary: in this tutorial, you’ll learn how to use the Python regex fullmatch() to match the whole string with a regular expression.

Introduction to the Python regex fullmatch function

The fullmatch() function returns a Match object if the whole string matches the search pattern of a regular expression, or None otherwise.

The syntax of the fullmatch() function is as follows:

re.fullmatch(pattern, string, flags=0)Code language: Python (python)
  • pattern specifies a regular expression to match.
  • string specifies the input string.
  • flags parameter is optional and defaults to zero. The flags parameter accepts one or more regex flags. The flags parameter changes how the regex engine matches the pattern.

Python regex fullmatch function example

The following example uses the fullmatch() function to validate an email address:

import re email = 'no-reply@pythontutorial.net' pattern = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]' match = re.fullmatch(pattern, email) if match is not None: print(f'The email " " is valid') else: print(f'The email " "" is not valid')Code language: Python (python)
The email "no-reply@pythontutorial.net" is validCode language: Python (python)

The following defines a function that uses the fullmatch() function to validate an email address. It returns True if the email is valid or raises a ValueError exception otherwise:

import re def is_email(s: str) -> bool: pattern = r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]' if re.fullmatch(pattern, s) is None: raise ValueError(f'The is not a valid email address') return TrueCode language: Python (python)

And you can use the is_email() function to validate an email like this:

if __name__ == '__main__': try: if is_email('no-reply@pythontutorial'): print('The email is valid') except ValueError as e: print(e)Code language: Python (python)
The no-reply@pythontutorial is not a valid email addressCode language: Python (python)

Python regex fullmatch vs match

Both fullmatch() and match() functions return a Match object if they find a match.

The fullmatch() function matches the whole string with a pattern while the match() function only finds a match at the beginning of the string. See the following example:

import re s = 'Python 3' pattern = 'Python' # fullmatch match = re.fullmatch(pattern, s) if match is not None: print('fullmatch:', match.group()) # search match = re.match(pattern, s) if match is not None: print('match:', match.group())Code language: Python (python)
match: PythonCode language: Python (python)

In this example, the fullmatch() returns None because the pattern Python only matches the beginning of the string, not the whole string.

On the other hand, the match() function matches the pattern at the beginning of the string and returns the match.

Both fullmatch() and search() functions return a Match object if they find a match of a pattern in a string. However, the fullmatch() matches the whole string while the search() matches anywhere in the string.

import re s = 'Python 3' pattern = '\d' # fullmatch match = re.fullmatch(pattern,s) if match is not None: print(match.group()) # search match = re.search(pattern,s) if match is not None: print(match.group()) # 3Code language: Python (python)
3Code language: Python (python)

In this example, the pattern \d matches a single digit. The fullmatch() function returns None because the whole string ‘Python 3’ doesn’t match.

However, the search() function returns a match because it could find the digit 3 at the end of the string.

Summary

  • Use the Python regex fullmatch() function to check if the whole string matches a pattern of a regular expression.

Источник

Оцените статью