Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way of checking if a string matches a pattern in python?

I have a string format that can be changed by someone else (just say)

sample = f"This is a {pet} it has {number} legs"

And I have currently two string

a = "This is a dog it has 4 legs"
b = "This was a dog"

How to check which string satisfies this sample format? I can use python's string replace() on sample and create regex of it and check using re.match. But the catch is sample can be changed, so statically using replace won't always work, as sample may get more place holders.

like image 365
coderelliot Avatar asked Nov 01 '25 10:11

coderelliot


1 Answers

A simple little way to extract objects out will be

import re

patt = re.compile(r'This is a (.+) it has (\d+) legs',)

a = "This is a dog it has 4 legs"
b = "This was a dog"
match = patt.search(a)
print(match.group(1), match.group(2))
like image 55
Supreet Sethi Avatar answered Nov 03 '25 00:11

Supreet Sethi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!