How to print matching strings in python with regex?

Member

by kadin , in category: Third Party Scripts , 14 days ago

How to print matching strings in python with regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 13 days ago

@kadin 

You can use the re module in Python to match strings with regular expressions. Here's an example of how you can print matching strings using regex in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import re

# Define the regular expression pattern
pattern = r'hello'

# Define the list of strings to match against
strings = ['hello world', 'hi there', 'hello python']

# Loop through each string and print it if it matches the pattern
for string in strings:
    if re.search(pattern, string):
        print(string)


In this example, the regular expression pattern r'hello' is defined to match the string 'hello'. The list of strings strings contains three strings, and the re.search() function is used to check if each string matches the pattern. If a string matches the pattern, it is printed to the console.


You can modify the pattern variable to match different string patterns using regular expressions.