Python - Check if a string matches a regular expression list

WBOY
Release: 2023-09-04 08:49:08
forward
1628 people have browsed it

Python - 检查字符串是否与正则表达式列表匹配

A regular expression, also known as a regular expression, is a sequence of characters that forms a search pattern. It is one of the powerful tools for pattern matching and manipulating strings. In python we have a module called re which helps in forming regular expressions.

Regular expressions patterns consist of ordinary characters (such as letters, numbers) and special characters called metacharacters. Metacharacters have special meanings and allow us to define complex search patterns. The following are some commonly used metacharacters in Python regular expressions.

  • . (dot) - Matches any single character except a newline character.

  • ^ (caret) − Matches the beginning of a string.

  • $ (USD) - Matches the end of a string.

  • * (asterisk) - Matches zero or more occurrences of the preceding pattern.

  • (plus sign) - Matches one or more occurrences of the preceding pattern.

  • ? (question mark) - Match zero or one occurrence of the preceding pattern.

  • [] (square brackets) - Defines a character class and matches any single character within the square brackets.

  • () (parentheses) - Group patterns and capture matching substrings.

  • \ (backslash) - Escape metacharacters or introduce special sequences.

Additional additional regular expressions support special sequences representing common patterns, as described below.

  • \d - Matches any number equivalent to [0-9].

  • \w - Matches any alphanumeric character equivalent to [a-zA-Z0-9_].

  • \s - matches any whitespace character.

  • \b - Matches word boundaries.

  • \A - matches the beginning of a string similar to ^ , but it does not consider multiline patterns.

  • \Z - matches the end of a string similar to $, but it does not consider multiline patterns.

There are several ways in Python to check if a string matches a list of regular expressions (regex). Let’s look at each method one by one.

Use re module

The "re" module in Python provides functions for working with regular expressions. We can use the 're.match()' function in the re module to check if a string matches a regex pattern and check the regex pattern list, which we can iterate over on the list and call 're.match()' for each pattern.

Example

In this example, the re.match() function is used to check whether a string matches each pattern in the regex_list. If a match is found, it will print the pattern.

import re
string = "Hello, Welcome to Tutorialspoint!"
regex_list = [r"Hello", r"\bWelcome\b", r"\d+"]
for pattern in regex_list:
   if re.match(pattern, string):
      print(f"String matches pattern: {pattern}")
Copy after login

Output

String matches pattern: Hello
Copy after login

Using list comprehension and re.search()

Another way to find matching patterns is to use a list comprehension and the re.search() function. By using a list comprehension without iterating the regular expression list, we can create a new list containing the matching pattern.

Example

In this example, we use a list comprehension and the line [pattern for pattern in regex_list if re.search(pattern, string)] to create a new list matching_patterns Contains regular expression patterns matching strings in regex_list. We then use the re.search() function to find the first occurrence of the pattern in the string.

import re
string = "Hello,happy learning!"
regex_list = [r"Hello", r"\bWelcome\b", r"\d+"]
matching_patterns = [pattern for pattern in regex_list if re.search(pattern, string)]
print("Matching patterns:", matching_patterns)
Copy after login

Output

Matching patterns: ['Hello']
Copy after login

Use any() function and re.search()

The

any() function is one of the functions available in Python that can be used to check whether any element in a regular expression list sequence is true. We can combine this with re.search() to check if any regular expression pattern matches the string.

Example

In this example, the any() function is used to iterate over the elements of the regular expression list and check if any pattern matches the string using re.search() . . If a match is found, it will print " string matches at least one pattern ".

import re
string = "Hello, Welcome to Tutorialspoint!"
regex_list = [r"Hello", r"\bWelcome\b", r"\d+"]
if any(re.search(pattern, string) for pattern in regex_list):
   print("String matches at least one pattern")
Copy after login

Output

String matches at least one pattern
Copy after login

The above is the detailed content of Python - Check if a string matches a regular expression list. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!