Will Curran
Will Curran

Reputation: 7110

What is the syntax for evaluating string matches on regular expressions?

How do I determine if a string matches a regular expression?

I want to find True if a string matches a regular expression.

Regular expression:

r".*apps\.facebook\.com.*"

I tried:

if string == r".*apps\.facebook\.com.*":

But that doesn't seem to work.

Upvotes: 1

Views: 1948

Answers (4)

Karmastan
Karmastan

Reputation: 5706

You're looking for re.match():

import re

if (re.match(r'.*apps\.facebook\.com.*', string)):
    do_something()

Or, if you want to match the pattern anywhere in the string, use re.search().

Why don't you also read through the Python documentation for the re module?

Upvotes: 0

PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

From the Python docs: on re module, regex

import re  
if re.search(r'.*apps\.facebook\.com.*', stringName):
    print('Yay, it matches!')

Since re.search returns a MatchObject if it finds it, or None if it is not found.

Upvotes: 3

wilhelmtell
wilhelmtell

Reputation: 58685

import re

match = re.search(r'.*apps\.facebook\.com.*', string)

Upvotes: 1

Alex Vidal
Alex Vidal

Reputation: 4108

You have to import the re module and test it that way:

import re

if re.match(r'.*apps\.facebook\.com.*', string):
    # it matches!

You can use re.search instead of re.match if you want to search for the pattern anywhere in the string. re.match will only match if the pattern can be located at the beginning of the string.

Upvotes: 2

Related Questions