Last Updated:
How to Extract S3 Bucket Name and Object Path from URLs Using Python: Regex & Solutions
Amazon Simple Storage Service (Amazon S3) is the backbone of cloud storage for modern data architectures, widely used for hosting static assets, data lakes, application backups, and machine learning datasets. When developing cloud applications, data pipelines, AWS Lambda triggers, or automation scripts, you will frequently encounter S3 resource identifiers in various URL formats—ranging from standard CLI URIs like s3://my-bucket/data/logs.json to HTTP virtual-hosted endpoints like https://my-bucket.s3.us-west-2.amazonaws.com/docs/report.pdf or presigned URLs with query strings.
To interact with these objects using the AWS SDK for Python (boto3)—such as calling s3_client.get_object(Bucket=bucket, Key=key) or s3_client.head_object()—you must reliably separate the bucket name from the object key (path).
However, parsing S3 URLs is not always straightforward. S3 URLs exist in several distinct formats, including S3 protocol URIs, virtual-hosted style endpoints, legacy path-style URLs, S3 Access Points, and S3 Express One Zone directory buckets. Furthermore, real-world URLs often contain query parameters, fragments, URL-encoded special characters, or bucket names containing dots.
In this guide, we will break down S3 URL structures and explore both regular expression (regex) and standard library (urllib.parse) Python solutions to extract S3 bucket names and object paths accurately.
Table of Contents#
- Understanding S3 URL Formats
- Regex Solutions for S3 URL Parsing
- Non-Regex Solutions Using
urllib.parse - Handling Common Edge Cases
- A Production-Ready, Unified S3 URL Parser
- Conclusion
- References
Understanding S3 URL Formats#
Before writing parsing logic, it is essential to understand the primary URL formats used across AWS services:
| URL Style | Example | Bucket / Target Location | Object Key Location |
|---|---|---|---|
S3 Protocol (s3://) | s3://my-bucket/path/to/data.csv | Host / Netloc (my-bucket) | Path after bucket (path/to/data.csv) |
| Virtual-Hosted (Global) | https://my-bucket.s3.amazonaws.com/path/to/data.csv | Subdomain before .s3. | Path (path/to/data.csv) |
| Virtual-Hosted (Regional) | https://my-bucket.s3.us-west-2.amazonaws.com/path/to/data.csv | Subdomain before .s3. | Path (path/to/data.csv) |
| Dual-Stack Endpoint | https://my-bucket.s3.dualstack.us-east-1.amazonaws.com/data.csv | Subdomain before .s3. | Path (data.csv) |
| Path-Style (Legacy) | https://s3.us-west-2.amazonaws.com/my-bucket/path/to/data.csv | First path segment (my-bucket) | Remaining path segments (path/to/data.csv) |
| S3 Access Point | https://my-ap-123456789012.s3-accesspoint.us-west-2.amazonaws.com/file.txt | Subdomain before .s3-accesspoint. | Path (file.txt) |
| S3 Express One Zone | https://bucket--usw2-az1--x-s3.s3express-usw2-az1.us-west-2.amazonaws.com/file.bin | Subdomain before .s3express- | Path (file.bin) |
Note on Path-Style URLs: AWS introduced virtual-hosted style as the standard format for all modern buckets. While legacy path-style URLs remain supported for existing configurations, new architectures should prioritize virtual-hosted style addressing.
Regex Solutions for S3 URL Parsing#
Regular expressions offer a concise way to validate and extract components from specific URL styles. Below are tailored regex patterns for each common URL format.
1. S3 Protocol URIs (s3://)#
The S3 URI protocol is used extensively across the AWS CLI, Apache Spark, AWS Glue, and data engineering pipelines.
Regex Pattern:
^s3://([^/]+)(?:/(.*))?$^s3://: Matches the scheme at the start of the string.([^/]+): Captures the bucket name (all characters up to the first slash).(?:/(.*))?$: Optionally matches the forward slash and captures the remaining object key (allowing empty or root keys).
Python Example:
import re
url = "s3://my-data-bucket/analytics/2026/report.parquet"
pattern = r"^s3://([^/]+)(?:/(.*))?$"
match = re.match(pattern, url)
if match:
bucket = match.group(1)
object_key = match.group(2) or ""
print(f"Bucket: {bucket}") # my-data-bucket
print(f"Object Key: {object_key}") # analytics/2026/report.parquet2. Virtual-Hosted Style URLs#
In virtual-hosted URLs, the bucket name resides in the subdomain preceding .s3., .s3-<region>, or .s3.dualstack.<region>.
Regex Pattern:
^https?://(.+?)\.s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?(?:/(.*))?$^https?://: Matcheshttp://orhttps://.(.+?): Non-greedily captures the bucket name (accommodating buckets with dots).\.s3: Matches the.s3domain marker.(?:[.-](?:dualstack\.)?[a-z0-9-]+)?: Matches optional regional specifiers (such as.us-west-2or-us-west-2) and dualstack flags.\.amazonaws\.com(?:\.cn)?: Matches standard AWS domains, including AWS China.(?:/(.*))?$: Captures the object key if present.
Python Example:
import re
url = "https://my-app-bucket.s3.us-west-2.amazonaws.com/uploads/avatar.png"
pattern = r"^https?://(.+?)\.s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?(?:/(.*))?$"
match = re.match(pattern, url)
if match:
bucket = match.group(1)
object_key = match.group(2) or ""
print(f"Bucket: {bucket}") # my-app-bucket
print(f"Object Key: {object_key}") # uploads/avatar.png3. Path-Style URLs#
In path-style URLs, the domain begins with s3 (e.g., s3.amazonaws.com or s3.us-west-2.amazonaws.com), and the bucket name is the first element of the URL path.
Regex Pattern:
^https?://s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?/([^/?#]+)(?:/(.*))?$^https?://s3...: Matches the host starting withs3./([^/?#]+): Captures the first path segment as the bucket name.(?:/(.*))?$: Captures any subsequent path segments as the object key.
Python Example:
import re
url = "https://s3.us-west-2.amazonaws.com/my-backup-bucket/db/dump.sql.gz"
pattern = r"^https?://s3(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?/([^/?#]+)(?:/(.*))?$"
match = re.match(pattern, url)
if match:
bucket = match.group(1)
object_key = match.group(2) or ""
print(f"Bucket: {bucket}") # my-backup-bucket
print(f"Object Key: {object_key}") # db/dump.sql.gz4. S3 Access Point URLs#
S3 Access Points simplify data access for shared datasets using hostnames ending with .s3-accesspoint.<region>.amazonaws.com.
Regex Pattern:
^https?://(.+?)\.s3-accesspoint(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?(?:/(.*))?$Python Example:
import re
url = "https://finance-ap-123456789012.s3-accesspoint.us-east-1.amazonaws.com/quarterly/q3.xlsx"
pattern = r"^https?://(.+?)\.s3-accesspoint(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?(?:/(.*))?$"
match = re.match(pattern, url)
if match:
access_point = match.group(1)
object_key = match.group(2) or ""
print(f"Access Point: {access_point}") # finance-ap-123456789012
print(f"Object Key: {object_key}") # quarterly/q3.xlsxNon-Regex Solutions Using urllib.parse#
While regular expressions are effective for pattern validation, Python’s standard urllib.parse module provides a cleaner, more readable approach to URL decomposition without external dependencies.
Parsing s3:// Protocol URIs#
For s3:// URLs, urlparse treats the bucket name as the network location (netloc) and the object key as the path:
from urllib.parse import unquote, urlparse
url = "s3://ml-datasets/training/v1/data%20matrix.csv"
parsed = urlparse(url)
bucket = parsed.netloc
# Strip leading slash and decode percent-encoded characters
object_key = unquote(parsed.path.lstrip("/"))
print(f"Bucket: {bucket}") # ml-datasets
print(f"Object Key: {object_key}") # training/v1/data matrix.csvParsing Virtual-Hosted Style URLs#
For HTTP/HTTPS virtual-hosted URLs, split the hostname (netloc) at the .s3 subdomain delimiter:
from urllib.parse import unquote, urlparse
url = "https://my.company.bucket.s3.eu-central-1.amazonaws.com/assets/logo.svg"
parsed = urlparse(url)
# Extract everything before '.s3' in the hostname
hostname = parsed.netloc.split(":")[0] # Remove port if present
bucket = hostname.split(".s3")[0]
object_key = unquote(parsed.path.lstrip("/"))
print(f"Bucket: {bucket}") # my.company.bucket
print(f"Object Key: {object_key}") # assets/logo.svgParsing Path-Style URLs#
For path-style URLs, the bucket name is the first segment of the path:
from urllib.parse import unquote, urlparse
url = "https://s3.amazonaws.com/company-archive/2026/archive.tar.gz"
parsed = urlparse(url)
# Split path into clean segments
segments = parsed.path.lstrip("/").split("/", 1)
bucket = segments[0]
object_key = unquote(segments[1]) if len(segments) > 1 else ""
print(f"Bucket: {bucket}") # company-archive
print(f"Object Key: {object_key}") # 2026/archive.tar.gzWorking with Boto3 and S3 APIs#
Once you extract the bucket name and object key, you can pass them directly to boto3:
import boto3
s3_client = boto3.client("s3")
# Extracted components
bucket_name = "my-data-bucket"
key_name = "analytics/report.parquet"
# Retrieve object metadata or download data
response = s3_client.get_object(Bucket=bucket_name, Key=key_name)
data = response["Body"].read()SDK Note: The official AWS SDK for Python (
boto3/botocore) requires explicitBucketandKeyarguments for most client operations. Becauseboto3does not expose a public S3 URL parsing function in its public API, developers implement a standalone parser or use utilities such assmart_open.parse_uri.
Handling Common Edge Cases#
Real-world applications must handle diverse URL permutations safely. Here is how to navigate common pitfalls:
URL Encoding in Object Keys (Spaces and Special Characters)#
Web browsers and HTTP clients encode special characters (e.g., spaces become %20 or +, brackets become %5B%5D). When interacting with S3 APIs via boto3, S3 expects the raw, decoded key name. Always wrap parsed paths in urllib.parse.unquote:
from urllib.parse import unquote
encoded_path = "user%20uploads/q1%2Bq2%20summary.pdf"
clean_key = unquote(encoded_path)
print(clean_key) # "user uploads/q1+q2 summary.pdf"Presigned URLs with Query Parameters and Fragments#
Presigned S3 URLs include authentication parameters (e.g., ?X-Amz-Signature=... or ?versionId=...) and optional URI fragments (#top).
Using urllib.parse.urlparse automatically separates the URL path from query strings (parsed.query) and fragments (parsed.fragment), ensuring query parameters do not corrupt the extracted object key.
Bucket Names Containing Dots#
Amazon S3 allows bucket names containing dots (e.g., logs.prod.example.com).
- Simple regex patterns like
([^.]+)fail on dotted bucket names because they terminate at the first dot. - By matching before
.s3or using non-greedy matches ((.+?)\.s3), your parser correctly isolates the full dotted bucket name.
Root Bucket Requests and Missing Object Keys#
URLs pointing to a bucket root (e.g., s3://my-bucket/ or https://my-bucket.s3.amazonaws.com/) have no object key. Ensure your parser strips slashes and returns an empty string "" rather than / or None.
A Production-Ready, Unified S3 URL Parser#
Here is a comprehensive, production-ready Python utility that handles s3://, virtual-hosted, path-style, access points, directory buckets, presigned parameters, and URL decoding in a single function:
import re
from typing import NamedTuple
from urllib.parse import unquote, urlparse
class S3Components(NamedTuple):
bucket: str
key: str
is_access_point: bool = False
def parse_s3_url(url: str) -> S3Components:
"""
Extracts the bucket name (or access point) and object key from an S3 URL.
Supports:
- S3 protocol URIs: s3://bucket/key
- Virtual-hosted URLs: https://bucket.s3.<region>.amazonaws.com/key
- Path-style URLs: https://s3.<region>.amazonaws.com/bucket/key
- Dual-stack, FIPS, and legacy regional endpoints
- S3 Access Points: https://ap-name.s3-accesspoint.<region>.amazonaws.com/key
- S3 Express One Zone: https://bucket--az--x-s3.s3express-az.<region>.amazonaws.com/key
- Presigned URLs with query strings and URL-encoded keys
"""
if not isinstance(url, str) or not url.strip():
raise ValueError("URL must be a non-empty string.")
parsed = urlparse(url.strip())
scheme = parsed.scheme.lower()
# 1. S3 Protocol URIs (s3://bucket/key)
if scheme == "s3":
bucket = parsed.netloc
key = unquote(parsed.path.lstrip("/"))
return S3Components(bucket=bucket, key=key, is_access_point=False)
# 2. HTTP / HTTPS endpoints
if scheme in ("http", "https"):
netloc = parsed.netloc.split(":")[0].lower() # Strip port if present
raw_path = parsed.path.lstrip("/")
# Check for Path-Style: s3.amazonaws.com/bucket/key or s3.<region>.amazonaws.com/bucket/key
path_style_pattern = r"^s3(?:[.-](?:dualstack\.)?(?:fips\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?$"
if re.match(path_style_pattern, netloc):
if not raw_path:
return S3Components(bucket="", key="", is_access_point=False)
parts = raw_path.split("/", 1)
bucket = parts[0]
key = unquote(parts[1]) if len(parts) > 1 else ""
return S3Components(bucket=bucket, key=key, is_access_point=False)
# Check for S3 Access Points
ap_pattern = r"^(.+?)\.s3-accesspoint(?:[.-](?:dualstack\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?$"
ap_match = re.match(ap_pattern, netloc)
if ap_match:
return S3Components(bucket=ap_match.group(1), key=unquote(raw_path), is_access_point=True)
# Check for S3 Express One Zone directory buckets
express_pattern = r"^(.+?)\.s3express-[a-z0-9-]+\.[a-z0-9-]+\.amazonaws\.com(?:\.cn)?$"
express_match = re.match(express_pattern, netloc)
if express_match:
return S3Components(bucket=express_match.group(1), key=unquote(raw_path), is_access_point=False)
# Check for Virtual-Hosted Style: <bucket>.s3...
vh_pattern = r"^(.+?)\.s3(?:[.-](?:dualstack\.)?(?:fips\.)?[a-z0-9-]+)?\.amazonaws\.com(?:\.cn)?$"
vh_match = re.match(vh_pattern, netloc)
if vh_match:
return S3Components(bucket=vh_match.group(1), key=unquote(raw_path), is_access_point=False)
raise ValueError(f"Unrecognized or unsupported S3 URL format: '{url}'")Running Test Verification#
test_cases = [
# S3 protocol URIs
"s3://my-bucket/path/to/object.txt",
"s3://my-bucket/",
"s3://my-bucket/path%20with%20spaces/report.pdf",
# Virtual-hosted style
"https://my-bucket.s3.amazonaws.com/path/to/object.txt",
"https://my.dotted.bucket.s3.us-west-2.amazonaws.com/docs/report.pdf",
"https://my-bucket.s3-us-west-2.amazonaws.com/images/photo.jpg",
"https://my-bucket.s3.dualstack.us-east-1.amazonaws.com/data.csv",
# Path style
"https://s3.amazonaws.com/my-bucket/path/to/object.txt",
"https://s3.us-west-2.amazonaws.com/my-bucket/logs/2026/output.json",
# Presigned URLs with query parameters & fragments
"https://my-bucket.s3.us-west-2.amazonaws.com/report.pdf?X-Amz-Signature=abc123#section2",
# S3 Access Point & S3 Express One Zone
"https://my-ap-123456789012.s3-accesspoint.us-west-2.amazonaws.com/reports/jan.csv",
"https://sample-bucket--usw2-az1--x-s3.s3express-usw2-az1.us-west-2.amazonaws.com/data/model.bin",
]
for url in test_cases:
result = parse_s3_url(url)
print(f"URL: {url}")
print(f"Result: Bucket/AP='{result.bucket}', Key='{result.key}', AP={result.is_access_point}\n")Conclusion#
Extracting S3 bucket names and object paths is a foundational requirement when building cloud automations, ETL pipelines, and SDK integrations in Python. While regular expressions offer precise validation for specific endpoint patterns, leveraging Python's urllib.parse alongside structured hostname matching ensures robust handling of edge cases—including bucket names with dots, presigned query parameters, and URL-encoded keys.
By using the unified parser provided above, your applications can reliably parse any standard S3 identifier across modern and legacy AWS endpoint configurations.