Siyu Qian
Siyu Qian

Reputation: 25

pattern.match with regex not working

import re

def test(stest):
    pattern = re.compile(r'/product\/(.*?)/i')

    result = pattern.match(stest)
    if result:
       print result.group()
    else:
       print "Doesn't match"

test('product/WKSGGPC104/GGPC-The-Paladin')

When I run the coding as the above, I will get "Doesn't match" for the result instead of 'product/'.

Could someone help me out? I have tested regular expression by using the online tool, it shows fine and matches the string that I am going to test.

Thank you for your help.

Upvotes: 1

Views: 78

Answers (2)

Jan
Jan

Reputation: 43199

A couple of issues with your code.
First, there was no / in the beginning, second, you provide the modifiers after the call:

import re

def test(stest):
    pattern = re.compile(r'product/([^/]+)'. re.IGNORECASE)

    result = pattern.match(stest)
    if result:
       print(result.group())
    else:
       print("Doesn't match")

test('product/WKSGGPC104/GGPC-The-Paladin')

See a demo on regex101.com.

Upvotes: 1

YashTD
YashTD

Reputation: 438

You are using string literals but still escaping the \ in your string.

Upvotes: 0

Related Questions