Python: finding a pattern in a string

I am trying to find a way to match pattern p in 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 must be true.

+4
source share
4 answers

I will convert your pattern into a regular expression, which can then be used re.match. For example, your xyzzyxbecomes (.+)(.+)(.+)\3\2\1$(the first occurrence of each letter becomes a capture group (.+), and subsequent occurrences become a valid backlink).

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))
+2
source

If I understand your question, you're looking for a Python approach to matching patterns by a set of strings.

Here is an example demonstrating the use of lists to achieve this.

, . , , . - JL

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

>>> 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']

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

Python , Match (string). match, : https://docs.python.org/3/library/re.html#match-objects

: s ( -)

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)

, !

0

.
:

, re.search()

:

import re 

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

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

if match:
    print('Yes!')
-1

Source: https://habr.com/ru/post/1589067/


All Articles