1

I have the following:

rule = "http://www.abc.com/"
test = "http://www.abc.com/test"
print(str(re.compile(rule).match(test)))

I want this to output None but instead it returns a match. How can I change the rule variable so the regex returns None?

3
  • You need to escape your periods in the rule by the way. If you don't, something like "http://www3abc3com/" might match. At least I think so... I could be wrong though. But try testing it out. Commented May 10, 2012 at 10:58
  • Wrap the regex with ^ and $ and escape the dots Commented May 10, 2012 at 10:58
  • Tried making rule = "^www\.abc\.com/$" but still no luck. What am I missing? edit: nevermind, fixed it Commented May 10, 2012 at 11:03

2 Answers 2

2

The ^ character matches the beginning of the string, and $ matches the end of the string. So you'd want:

rule = "^http://www\.abc\.com/$"
test = "http://www.abc.com/test"
print(str(re.compile(rule).match(test)))

Note that . means "match any character" so if you want to match an actual . you need the \ before it.

Sign up to request clarification or add additional context in comments.

2 Comments

Just curious, is the ^ necessary since python's match automatically starts at the beginning of the string?
Yes, you're right. If you're using match, it's not necessary. If you're using search instead of match however, it it necessary.
2

I do not think that you need regexp here if you wish to compare full strings. Please correct me if I misunderstand you. :)

May be this code will be uesful:

rule = "http://www.abc.com/"
test = "http://www.abc.com/test"
print(rule == test)

Returns False if strings are different, True otherwise.

1 Comment

Of course I can just check for equality, but unfortunately I do need regexp in this current situation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.