How to use RegEx inside lambda Expression

Published on Aug. 22, 2023, 12:15 p.m.

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'].

Tags: