Skip to content

Python search string for a pattern | Example code

  • by

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 the 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 the string matches the 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 or suggestions on this string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *