Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Find pattern in a string

Tags:

python

string

I am trying to find a way to match a pattern p in a string s in python.

s = 'abccba'
ss = 'facebookgooglemsmsgooglefacebook'
p = 'xyzzyx'
# s, p -> a, z  # s and p can only be 'a' through 'z'

def match(s, p):
   if s matches p:
      return True
   else:
      return False

match(s, p) # return True
match(ss, p) # return True

I just tried:

import re

s = "abccba"
f = "facebookgooglemsmsgooglefacebook"
p = "xyzzyx"

def fmatch(s, p):
    p = re.compile(p)
    m = p.match(s)
    if m:
        return True
    else:
        return False

print fmatch(s, p)
print fmatch(f, p)

Both return false; they are supposed to be true.

like image 975
user3480774 Avatar asked May 20 '15 19:05

user3480774


3 Answers

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))
like image 197
Stefan Pochmann Avatar answered Sep 24 '22 18:09

Stefan Pochmann


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!')
like image 32
Tenzin Avatar answered Sep 26 '22 18:09

Tenzin


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']
like image 23
jatal Avatar answered Sep 23 '22 18:09

jatal