How to store matched part of regex in python?

Member

by orpha , in category: Third Party Scripts , 4 months ago

How to store matched part of regex in python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 4 months ago

@orpha 

In Python, you can store the matched part of a regular expression by using the re module.


Here's an example to demonstrate how to store the matched part of a regex in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import re

# Define the regex pattern
pattern = r'(d{2}-d{2}-d{4})'

# Input text
text = 'Date of birth: 12-31-2000'

# Search for the pattern in the text
match = re.search(pattern, text)

# If a match is found
if match:
    # Store the matched part in a variable
    matched_part = match.group(1)
    
    # Print the matched part
    print(matched_part)


In this example, the regex pattern (d{2}-d{2}-d{4}) is used to match a date format in the input text. The re.search() function is used to search for the pattern in the text. If a match is found, the group(1) method is used to store the matched part in the variable matched_part. Finally, the matched part is printed to the console.

Related Threads:

How to replace part of a url with regex?
How to extract part of string using regex?
How to extract part of string in bash using regex
How to exclude part of the text via regex in php?
How to remove part of file name using a regex expression?
How to store dictionary in redis from python?