Naxey
Naxey

Reputation: 506

Lookahead and Lookbehind regex

So I have this regex: (?:\/p\/|$)(?:[^\/]*)(?<=-)(.*)(?=\/)

and I want it to pull the id out of Ikea links but it seems not to work with Go. Can anyone help me with that? or is there a tool to just convert it?

I got it to work with all the other flavors but not Go.

https://regex101.com/r/74RITp/4 <-- with examples here

Upvotes: 1

Views: 1169

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

You may remove the lookarounds completely and rely on the capturing mechanism using:

/p/[^/]*-([^/]*)/

See the regex demo. Note the leading and trailing / is part of the string pattern. Details:

  • /p/ - a /p/ string
  • [^/]* - zero or more chars other than /
  • - - a hyphen
  • ([^/]*) - Group 1: zero or more chars other than /
  • / - a / char.

See the Golang demo:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := `https://www.ikea.com/de/de/p/symfonisk-tischleuchte-mit-wifi-speaker-weiss-30435157/?tduid=d8b332c221610a36288c647f8959959f&utm_medium=affiliate&utm_name=generic&utm_term=conversion&utm_content=deeplink&utm_source=SmartApfel`
    regex := regexp.MustCompile(`/p/[^/]*-([^/]*)/`)
    fmt.Printf("%#v\n", regex.FindStringSubmatch(s)[1])
}

Output: "30435157"

Upvotes: 3

Related Questions