【问题标题】:How to combine regex, group them dynamically in javascript?如何结合正则表达式,在javascript中动态分组?
【发布时间】:2018-05-23 07:37:08
【问题描述】:

我需要使用 JSON 下面的 allowedPattern、MinLength 和 MaxLength 属性来形成正则表达式。我正在使用分组,它工作正常。

1) "DomainNetBIOSName" : {
  "Description" : "NetBIOS name of the domain (upto 15 characters) for users of earlier versions of Windows e.g. CORP",
  "Type" : "String",
  "MinLength" : "3",
  "MaxLength" : "15",
  "AllowedPattern" : "[a-zA-Z0-9]+"
},   

从上面的 json 中使用 minlength、maxlength 和允许的模式,我将形成这样的正则表达式 - ([a-zA-Z0-9]+){3,15} 验证工作正常。

现在如果我有这样的 json -

2)  "SourceCidrForRDP" : {
  "Description" : "IP Cidr from which you are likely to RDP into the instances. You can add rules later by modifying the created security groups e.g. 54.32.98.160/32",
  "Type" : "String",
  "MinLength" : "9",
  "MaxLength" : "18",
  "AllowedPattern" : "^([0-9]+\.){3}[0-9]+\/[0-9]+$"
}

正则表达式的分组不适用于此示例-

 From above json using same logic forming the regex like this - (^([0-9]+\.){3}[0-9]+\/[0-9]+$){9,18}$ which failing because of added length validation {9,18}. 

我想使用 minLength、maxLength 和允许的模式形成一个组合的正则表达式。需要一种适用于所有此类情况的解决方案吗?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    {min, max} 不代表匹配的 minLengthmaxLength。它说“在 minmax 次之间匹配上一个令牌”。

    这意味着第一个似乎有效的正则表达式 (([a-zA-Z0-9]+){3,15}) 无效。它将匹配所有字母数字序列,即使它超过 15 个字符。

    你想要的是这个: ^([a-zA-Z0-9]{3,15})$(没有+)。它将匹配单个字母数字字符 3 到 15 次,并对结果序列进行分组。它不会接受短于 3 个字符的字符串和长于 15 个字符的字符串。

    对于您的第二个正则表达式,不需要 minLengthmaxLength,正则表达式可以强制字符串表示 IP Cidr:

    ^((?:\d{1,3}.){3}\d{1,3})\/(\d{1,2})$ (regexr explaination)

    这将检索 IP 并将其分为两组:192.168.0.024(当给定 192.168.0.0/24 时)。

    因此不需要最小和最大长度,因为正则表达式已经强制用户遵循模式。您可以删除 minLength 和 maxLength 检查(或根据您的正则表达式是否需要它使其成为可选)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多