Table of Contents
Use wildcards to match strings:
Use regular expressions to match strings using wildcards
Home Backend Development Python Tutorial How to use wildcards to match strings in Python

How to use wildcards to match strings in Python

May 06, 2023 pm 12:13 PM
python

Use wildcards to match strings:

  • Use the fnmatch.filter() method to get the strings matching the pattern from the list.

  • Use the fnmatch.fnmatch() method to check whether a string matches a pattern.

import fnmatch

a_list = ['fql.txt', 'jiyik.txt', 'com.csv']

pattern = '*.txt'
filtered_list = fnmatch.filter(a_list, pattern)
print(filtered_list)  # ????️ ['fql.txt', 'jiyik.txt']
Copy after login

How to use wildcards to match strings in Python

If we prefer to use regular expressions, please scroll down to the next subtitle.

fnmatch.filter method accepts an iterable object and a pattern and returns a new list containing only the iterable object elements that match the provided pattern.

The pattern in the example starts with any one or more characters and ends with .txt.

The pattern in the example contains only one wildcard, but you can use as many wildcards as you want.

Note that the asterisk * matches everything (one or more characters).

If you want to match any single character, replace the asterisk * with the question mark ?.

  • * Matches everything (one or more characters)

  • ? Matches anything A single character

  • [sequence] matches any character in the sequence

  • [!sequence] Matches any non-sequential characters

Here is an example of using a question mark to match any single character.

import fnmatch

a_list = ['abc', 'abz', 'abxyz']

pattern = 'ab?'
filtered_list = fnmatch.filter(a_list, pattern)
print(filtered_list)  # ????️ ['abc', 'abz']
Copy after login

This pattern matches a string starting with ab followed by any single character.

If you want to use wildcards to check whether a string matches a pattern, use the fnmatch.fnmatch() method.

import fnmatch

a_string = '2023_jiyik.txt'
pattern = '2023*.txt'

matches_pattern = fnmatch.fnmatch(a_string, pattern)
print(matches_pattern)  # ????️ True

if matches_pattern:
    # ????️ this runs
    print('The string matches the pattern')
else:
    print('The string does NOT match the pattern')
Copy after login

The pattern starts with 2023, followed by any one or more characters, and ends with .txt.

fnmatch.fnmatch The method accepts a string and a pattern as parameters. If the string matches the pattern, the method returns True, otherwise it returns False. Just replace the asterisk * with the question mark ? if you want to match any single character instead of any one or more characters.

Alternatively, we can use regular expressions.

Use regular expressions to match strings using wildcards

Use wildcards to match strings:

Use re.match() Method checks if a string matches the given pattern. Use .* characters instead of wildcard characters. The

import re

a_list = ['2023_fql.txt', '2023_jiyik.txt', '2023_com.csv']

regex = re.compile(r'2023_.*\.txt')

list_of_matches = [
    item for item in a_list
    if re.match(regex, item)
]

print(list_of_matches)  # ????️ ['2023_fql.txt', '2023_jiyik.txt']
Copy after login
Copy after login

re.compile method compiles a regular expression pattern into an object that can be used using its match() or search() method to match.

This is more efficient than using re.match or re.search directly because it saves and reuses the regular expression object.

Regular expression starts with 2023_.

The .* characters in regular expressions are used as wildcards to match any one or more characters.

  • Dot . matches any character except a newline character.

  • The asterisk * matches the preceding regular expression (dot .) zero or more times.

We use the backslash\ character to escape dots. in the extension because, as we saw before, the dot . has a special meaning when used in regular expressions. In other words, we use backslashes to handle dots. as literal characters.

We use list comprehension to iterate over the list of strings.

List comprehensions are used to perform certain operations on each element or to select a subset of elements that meet a condition.

In each iteration, we use the re.match() method to check if the current string matches the pattern.

import re

a_list = ['2023_fql.txt', '2023_jiyik.txt', '2023_com.csv']

regex = re.compile(r'2023_.*\.txt')

list_of_matches = [
    item for item in a_list
    if re.match(regex, item)
]

print(list_of_matches)  # ????️ ['2023_fql.txt', '2023_jiyik.txt']
Copy after login
Copy after login

The re.match method returns a match object if the provided regular expression matches in the string.

If the string does not match the regular expression pattern, the match() method returns None.

The new list contains only the strings in the original list that match the pattern.

If you only want to match any single character, remove the asterisk after the dot *. in the regular expression.

import re

a_list = ['2023_a.txt', '2023_bcde.txt', '2023_z.txt']

regex = re.compile(r'2023_.\.txt')

list_of_matches = [
    item for item in a_list
    if re.match(regex, item)
]

print(list_of_matches)  # ????️ ['2023_a.txt', '2023_z.txt']
Copy after login

Dot . Matches any character except newlines.

By using dots . without escaping, the regular expression matches anything starting with 2023_ followed by any single character ending with ## The string ending in #.txt.

If you need help reading or writing regular expressions, please refer to our regular expression tutorial.

This page contains a list of all special characters and many useful examples.

If you want to use regular expressions to check whether a string matches a pattern, we can directly use the

re.match() method.

import re

a_string = '2023_fql.txt'

matches_pattern = bool(re.match(r'2023_.*\.txt', a_string))
print(matches_pattern)  # ????️ True

if matches_pattern:
    # ????️ this runs
    print('The string matches the pattern')
else:
    print('The string does NOT match the pattern')
Copy after login

如果字符串与模式匹配,则 re.match() 方法将返回一个匹配对象,如果不匹配,则返回 None

我们使用 bool() 类将结果转换为布尔值。

如果要对单个字符使用通配符,请删除星号 *

import re

a_string = '2023_ABC.txt'

matches_pattern = bool(re.match(r'2023_.\.txt', a_string))
print(matches_pattern)  # ????️ False

if matches_pattern:
    print('The string matches the pattern')
else:
    # ????️ this runs
    print('The string does NOT match the pattern')
Copy after login

请注意 ,点 . 我们没有使用反斜杠作为前缀用于匹配任何单个字符,而点 . 我们以反斜杠 \ 为前缀的被视为文字点。

示例中的字符串与模式不匹配,因此 matches_pattern 变量存储一个 False 值。

The above is the detailed content of How to use wildcards to match strings in Python. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles