【问题标题】:Azure Container Name RegExAzure 容器名称正则表达式
【发布时间】:2016-05-09 20:58:04
【问题描述】:

如何使用正则表达式验证 Azure 容器名称?我从其他帖子中找到了以下代码行,但它没有验证连续的破折号 (-)。

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

例如以下字符串在上述正则表达式模式下被认为是有效的:

test--test 

规则是:

  • 3 到 63 个字符;
  • 以字母或数字开头;
  • 包含字母、数字和破折号 (-);
  • 每个破折号 (-) 必须紧跟在字母或数字的前面和后面

【问题讨论】:

  • 这个正则表达式包含一个用户错误:我相信这个[a-z0-9\-[^\-] 部分没有按照作者的意图进行匹配。它意味着匹配什么样的字符串?有什么要求?
  • - 3 到 63 个字符; - 以字母或数字开头; - 包含字母、数字和破折号 (-); - 每个破折号 (-) 必须紧跟在一个字母或数字之前和之后

标签: regex c#-4.0 asp.net-web-api2 azure-blob-storage asp.net-web-api-routing


【解决方案1】:

我知道这不完全是您所要求的,但您可以使用存储客户端库中内置的方法,而不是滚动您自己的正则表达式:Microsoft.Azure.Storage.NameValidator.ValidateContainerName(myContainerName)

如果名称无效,则此方法将抛出 ArgumentException。正如您从名称中猜到的那样,这个静态类包含用于验证队列、表、blob、目录和其他名称的方法。

【讨论】:

  • 在撰写此评论时,NameValidator.ValidateBlobName 似乎不起作用,而 NameValidator.ValidateContainerName 工作正常。所以要小心使用NameValidator中的验证方法。
【解决方案2】:

如果您按照自定义方式解决问题,则可以使用

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

regex demo

如果字符串中有 2 个连续的连字符,(?!.*--) 前瞻将导致匹配失败。

现在,谈谈Microsoft.WindowsAzure.Storage.NameValidator.ValidateContainerName(string containerName):代码只是重复上述正则表达式的逻辑每个问题都有单独的参数异常

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

这两行设置容器名称的最小和最大长度,并在private static void ValidateShareContainerQueueHelper(string resourceName, string resourceType) 方法中进行检查。那里使用的正则表达式是

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

所以,如果你添加长度限制,这个模式就是你所需要的:

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

此正则表达式是答案顶部的“同义词”。

如果您需要不同的ArgumentExceptions 来表示不同的问题,您应该使用NameValidator 方法。 否则,您可以使用您的单一正则表达式解决方案。

【讨论】:

    【解决方案3】:

    在 Powershell 中,您可以这样做:

    function Test-ContainerNameValidity($ContainerName)
    {
        Import-Module -Name AzureRM
        Write-Host "Testing container name against Microsoft's naming rules."
        try {
            [Microsoft.WindowsAzure.Storage.NameValidator]::ValidateContainerName($ContainerName)
            Write-Host -ForegroundColor Green "Container name is valid!"
            return
        }
        catch {
            Write-Host -ForegroundColor Red "Invalid container name. Please check the container name rules: https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata#container-names"
            Write-Host -ForegroundColor Red "The script is now exiting."
            exit
        }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-11
      • 2019-08-09
      • 2010-09-21
      • 2023-04-09
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多