The Python Oracle

How do I check if a string matches a set pattern in Python?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle

--

Chapters
00:00 How Do I Check If A String Matches A Set Pattern In Python?
00:39 Accepted Answer Score 6
01:14 Answer 2 Score 3
01:52 Thank you

--

Full question
https://stackoverflow.com/questions/4529...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #patternmatching

#avk47



ACCEPTED ANSWER

Score 6


import re

string = 'the apple is red'

re.search(r'^the (apple|orange|grape) is (red|orange|violet)', string)

Here's an example of it running:

In [20]: re.search(r'^the (apple|orange|grape) is (red|orange|violet)', string). groups()
Out[20]: ('apple', 'red')

If there are no matches then re.search() will return nothing.

You may know "next to nothing about regex" but you nearly wrote the pattern.

The sections within the parentheses can also have their own regex patterns, too. So you could match "apple" and "apples" with

r'the (apple[s]*|orange|grape)




ANSWER 2

Score 3


The re based solutions for this kind of problem work great. But it would sure be nice if there were an easy way to pull data out of strings in Python without have to learn regex (or to learn it AGAIN, which what I always end up having to do since my brain is broken).

Thankfully, someone took the time to write parse.

parse

parse is a nice package for this kind of thing. It uses regular expressions under the hood, but the API is based on the string format specification mini-language, which most Python users will already be familiar with.

For a format spec you will use over and over again, you'd use parse.compile. Here is an example:

>>> import parse
>>> theaisb_parser = parse.compile('the {} is {}')
>>> fruit, color = theaisb_parser.parse('the apple is red')
>>> print(fruit, color)
apple red