URL Path Segment
Match individual `/segment` parts of a URL path, capturing each one.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("\\/([^\\/?#\\s]+)", "g");
const input = "/users/42/posts?page=2";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"\/([^\/?#\s]+)")
input_text = "/users/42/posts?page=2"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
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.
Pattern
\/([^\/?#\s]+) (flags: g)Raw source: \/([^\/?#\s]+)
How it works
Examples
Input
/users/42/posts?page=2Matches
/users/42/posts
Input
/api/v1/healthMatches
/api/v1/health
Input
no/pathNo match
—Common use cases
- •Routing-table introspection
- •URL normalization / rewriting
- •Analytics: per-path-segment aggregation
- •API gateway pattern matching
Related patterns
OpenAPI Path Template
WebMatch OpenAPI / Express-style path templates with `{param}` (or `:param` after substitution) placeholders.
Twitter / X URL
WebMatch Twitter/X profile and status URLs, capturing the handle and (optional) tweet ID.
URL Query String
WebExtract the query string portion of a URL (everything between `?` and `#` or end-of-string).
URL Slug
WebValidate URL slugs: lowercase letters and digits separated by single hyphens, no leading/trailing hyphens.