The Python Oracle

Python: Find pattern in a string

--------------------------------------------------
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: Hypnotic Orient Looping

--

Chapters
00:00 Python: Find Pattern In A String
00:32 Answer 1 Score 0
00:59 Answer 2 Score 3
01:18 Answer 3 Score 1
02:03 Accepted Answer Score 7
02:36 Thank you

--

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

--

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

--

Tags
#python #string

#avk47



ACCEPTED ANSWER

Score 7


I convert your pattern into a regular expression that can then be used by re.match. For example, your xyzzyx becomes (.+)(.+)(.+)\3\2\1$ (the first occurrence of each letter becomes a capture group (.+), and subsequent occurences become the proper back reference).

import re

s = 'abccba'
ss = 'facebookgooglemsmsgooglefacebook'
p = 'xyzzyx'

def match(s, p):
    nr = {}
    regex = []
    for c in p:
        if c not in nr:
            regex.append('(.+)')
            nr[c] = len(nr) + 1
        else:
            regex.append('\\%d' % nr[c])
    return bool(re.match(''.join(regex) + '$', s))

print(match(s, p))
print(match(ss, p))



ANSWER 2

Score 3


You could make use of regular expressions.
Have a look here for some examples: Link

I think you could use re.search()

Ecample:

import re 

stringA = 'dog cat mouse'
stringB = 'cat'

# Look if stringB is in stringA
match = re.search(stringB, stringA)

if match:
    print('Yes!')



ANSWER 3

Score 1


If I'm understanding your question, you're looking for a pythonic approach to pattern matching across a set of strings.

Here is an example demonstrating the use of list comprehensions to achieve this goal.

I hope it helps you reach your goal. Please let me know if I can help further. - JL

Demonstrate No Match Found

>>> import re
>>> s = ["abccba", "facebookgooglemsmsgooglefacebook"]
>>> p = "xyzzyx"
>>> result = [ re.search(p,str) for str in s ] 
>>> result
[None, None]

Demonstrate Combination of Matches and No Match in the result

>>> p = "abc"
>>> result = [ re.search(p,str) for str in s ] 
>>> result
[<_sre.SRE_Match object at 0x100470780>, None]
>>> [ m.group(0) if m is not None else 'No Match' for m in result ]
['abc', 'No Match']
>>> [ m.string if m is not None else 'No Match' for m in result ]
['abccba', 'No Match']

Demonstrate single statement

>>> [ m.string if m is not None else 'No Match' for m in [re.search(p,str) for str in s] ]
['abccba', 'No Match']



ANSWER 4

Score 0


Compile a Python regular expressions object for some pattern of interest and then pass the string to its Match(string) method. You'll want to use a match object if you need a boolean output: https://docs.python.org/3/library/re.html#match-objects

Example: Check string s for any word character (that is, alphanumerics)

def match_string(s):
    ##compile a regex for word characters
    regex = re.compile("\\w") 
    ##return the result of the match function on string 
    return re.match(s)

Hope it helps!