Skip to content

Instantly share code, notes, and snippets.

@Martinsos
Last active April 6, 2025 17:10
Show Gist options
  • Select an option

  • Save Martinsos/34d962b81b01082a45d90b2af5988097 to your computer and use it in GitHub Desktop.

Select an option

Save Martinsos/34d962b81b01082a45d90b2af5988097 to your computer and use it in GitHub Desktop.
Regex for parsing Azure Blob URI (javascript)
/**
* Validates and parses given blob uri and returns storage account, container and blob names.
* @param {string} blobUri - Valid Azure storage blob uri.
* Check link for more details: https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata#resource-uri-syntax .
* Few examples of valid uris:
* - https://myaccount.blob.core.windows.net/mycontainer/myblob
* - http://myaccount.blob.core.windows.net/myblob
* - https://myaccount.blob.core.windows.net/$root/myblob
* @returns {Object} With following properties:
* - {string} storageAccountName
* - {string} containerName
* - {string} blobName
* @throws {Error} If blobUri is not valid blob uri.
*/
const parseAzureBlobUri = (blobUri) => {
const ERROR_MSG_GENERIC = 'Invalid blob uri.'
const storageAccountRegex = new RegExp('[a-z0-9]{3,24}')
const containerRegex = new RegExp('[a-z0-9](?!.*--)[a-z0-9-]{1,61}[a-z0-9]')
const blobRegex = new RegExp('.{1,1024}') // TODO: Consider making this one more precise.
const blobUriRegex = new RegExp(
`^http[s]?:\/\/(${ storageAccountRegex.source })\.blob.core.windows.net\/`
+ `(?:(\$root|(?:${ containerRegex.source }))\/)?(${ blobRegex.source })$`
)
const match = blobUriRegex.exec(blobUri)
if (!match) throw Error(ERROR_MSG_GENERIC)
return {
storageAccountName: match[1],
containerName: match[2] || '$root', // If not specified, then it is implicitly root container with name $root.
blobName: match[3]
}
}
export default parseAzureBlobUri
@Martinsos
Copy link
Author

While there is a method for parsing Azure Blob Uri in some of Azure SDKs, there is no such method (at least to my knowledge) in azure sdk for nodejs/javascript. I tried searching for regex online but could not find it, so I created my own and thought it would be useful to make it public in case somebody else needs the same thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment