Search code examples
pythonpython-3.xregexregex-groupregex-negation

Python Regex match numbers after words


I am looking to match separately the numbers contained in the following type of string using regex:

https://www.pizza.com/word1/685185197419/word2/980054970331342/

output:

w1 = 685185197419
w2 = 980054970331342

I am using this expression but it does not work properly: \word1(.*)[0-9]\/


Solution

  • You need to specify where to find each digit sequences. Also, you can use named groups, which can match the variables you want at the end

    s = "https://www.pizza.com/word1/685185197419/word2/980054970331342/"
    
    r = re.match(r"^.*word1/(?P<w1>\d+)/word2/(?P<w2>\d+)/$", s)
    
    w1 = r.group("w1")
    w2 = r.group("w2")