Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Container Name RegEx

How to validate Azure Container name using regex? I found the following line of code from some other post, but it is not validating the consecutive dashes (-).

if (!Regex.IsMatch(containerName, @"^[a-z0-9](([a-z0-9\-[^\-])){1,61}[a-z0-9]$"))
 throw new Exception("Invalid container name);

E.g. the following string is considered valid with the above regex pattern:

test--test 

The rules are:

  • 3 to 63 Characters;
  • Starts With Letter or Number;
  • Contains Letters, Numbers, and Dash (-);
  • Every Dash (-) Must Be Immediately Preceded and Followed by a Letter or Number
like image 540
Mukil Deepthi Avatar asked Feb 01 '16 12:02

Mukil Deepthi


2 Answers

I know it's not exactly what you asked, but rather than rolling your own regex, you can use a method that is built into the storage client library: Microsoft.Azure.Storage.NameValidator.ValidateContainerName(myContainerName)

If the name is not valid then this method throws an ArgumentException. As you would guess from the name, this static class contains methods for validating names of queues, tables, blobs, directories and others.

like image 138
knightpfhor Avatar answered Oct 03 '22 05:10

knightpfhor


If you follow your custom way of solving the issue, you can use

^[a-z0-9](?!.*--)[a-z0-9-]{1,61}[a-z0-9]$

See regex demo

The (?!.*--) lookahead will fail a match if there are 2 consecutive hyphens in the string.

Now, speaking about the Microsoft.WindowsAzure.Storage.NameValidator.ValidateContainerName(string containerName): the code is just repeating the logic of the regex above with separate argument exceptions per issue.

private const int ContainerShareQueueTableMinLength = 3;
private const int ContainerShareQueueTableMaxLength = 63;

These two lines set the min and max length of the container name and are checked against in the private static void ValidateShareContainerQueueHelper(string resourceName, string resourceType) method. The regex used there is

private static readonly Regex ShareContainerQueueRegex = 
    new Regex("^[a-z0-9]+(-[a-z0-9]+)*$", NameValidator.RegexOptions);

So, this pattern is all you need if you add the length restriction to it:

^(?=.{3,63}$)[a-z0-9]+(-[a-z0-9]+)*$
 ^^^^^^^^^^^^

This regex is a "synonym" of the one at the top of the answer.

You should use the NameValidator approach if you need different ArgumentExceptions to signal different issues. Else, you may use your one-regex solution.

like image 38
Wiktor Stribiżew Avatar answered Oct 03 '22 05:10

Wiktor Stribiżew