Python search string for a pattern | Example code

Use a Regex object’s search() method to search the string it is passed for any matches to the pattern in Python. Match objects have a group() method that will return the actual matched text from the searched string.

Python search string for a pattern example

Simple example code Matching regex pattern for phone number. You have to import the re module for this example.

import re

pattern = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = pattern.search('John number is 415-555-4242.')

print('Phone number: ' + mo.group())

Output:

Python search string for a pattern

Another example

Python Find pattern in a string. Convert your pattern into a regular expression that can then be used by re.match.

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))

Output:

True
True

Check if string matches pattern

Check if a string matches this pattern. That should work for an uppercase, number pattern.

import re
pattern = re.compile("^([A-Z][0-9]+)+$")
pattern.match(string)

Do comment if you have any doubts and suggestions on this string topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.