深度阅读

How to use RegEx inside lambda Expression

作者
作者
2023年08月22日
更新时间
9.22 分钟
阅读时间
0
阅读量

If you want to use regular expressions inside a lambda expression in Python, you can use the re module to define a regular expression pattern, and then use the re module’s search() or match() functions to search for that pattern in a string.

Here’s an example of how you can use a regular expression inside a lambda function to filter a list of strings:

import re

strings = ['abc123', 'def456', 'ghi789', 'jkl', 'mno0']

filtered_list = list(filter(lambda s: re.match(r'\w+\d+', s), strings))

print(filtered_list)

In this example, the lambda function uses re.match to search for a pattern that matches one or more word characters followed by one or more digits. The filter() function applies this lambda function to each element in strings, and returns only the elements that match the regular expression pattern. The resulting filtered_list will contain ['abc123', 'def456', 'ghi789'].

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。