简体   繁体   中英

match python regex url exactly

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM