Go (RE2)

URL Path Segment in GO

Match individual `/segment` parts of a URL path, capturing each one.

Try it in the GO tester →

Pattern

regexGO
\/([^\/?#\s]+)   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`\/([^\/?#\s]+)`)
	input := `/users/42/posts?page=2`
	for _, match := range re.FindAllString(input, -1) {
		fmt.Println(match)
	}
}

Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.

How the pattern works

\/ matches the literal slash. ([^\/?#\s]+) captures one or more characters that aren't a slash, question mark, hash, or whitespace — i.e. one path segment. Useful for breaking apart a URL into its component pieces.

Examples

Input

/users/42/posts?page=2

Matches

  • /users
  • /42
  • /posts

Input

/api/v1/health

Matches

  • /api
  • /v1
  • /health

Input

no/path

No match

Same pattern, other engines

← Back to URL Path Segment overview (all engines)