如何使用正则表达式验证文化代码?

Sam*_*e69 17 regex

我真的不懂正则表达式,我也找不到任何正则表达式规则来验证文化代码:en-GB,en-UK,az-AZ-Cyrl,其他.

如何使用正则表达式验证这些代码?

Col*_*ert 32

你可以用这个验证:

/^[a-z]{2,3}(?:-[A-Z]{2,3}(?:-[a-zA-Z]{4})?)?$/
Run Code Online (Sandbox Code Playgroud)

下面是它的工作原理

^       <- Starts with
[a-z]   <- From a to z (lower-case)
{2,3}   <- Repeated at least 2 times, at most 3
(?:     <- Non capturing group
   -        <- The "-" character
   [A-Z]     <- From a to z (upper-case)
   {2,3}     <- Repeated at least 2 times, at most 3
   (?:       <- Non capturing group
       -         <- The "-" character
       [a-zA-Z]  <- from a to Z (case insensitive)
       {4}      <- Repeated 4 times
   )         <- End of the group
   ?         <- Facultative
 )       <- End of the group
 ?       <- Facultative
 $       <- Ends here
Run Code Online (Sandbox Code Playgroud)

(?:-(?:Cyrl|Latn))?如果唯一的选项是Cyrl和Latn,您也可以替换最后一个非捕获组

  • @Stephane,w3.org在这里并不是真正的规范(不是用于识别语言的标签),实际上提供的正则表达式并不严格遵守RFC.实际上遵循rfc4646 2.1需要稍微复杂一点的东西.我的解决方案的优势"不是真正的"是它尊重OP提供的列表并且会减少误报.问题是它不尊重RFC,并且列表中没有的一个语言/变体/区域可能无效. (2认同)
  • 这个正则表达式不符合RFC1766兼容的语言环境标识符,因为它没有专门处理`i-`或`x-`前缀语言环境,例如`i-sami-no`和`x-klingon`都不会匹配这个.以下答案更准确:http://stackoverflow.com/a/3962783/83444 (2认同)

Pat*_*ira 6

这是我在Dublin Core/W3C xsd中找到的:http://www.w3.org/2001/XMLSchema

  <xs:simpleType name="language" id="language"> 
    <xs:annotation> 
      <xs:documentation 
        source="http://www.w3.org/TR/xmlschema-2/#language"/> 
    </xs:annotation> 
    <xs:restriction base="xs:token"> 
      <xs:pattern 
        value="[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*"
                id="language.pattern"> 
        <xs:annotation> 
          <xs:documentation 
                source="http://www.ietf.org/rfc/rfc3066.txt"> 
            pattern specifies the content of section 2.12 of XML 1.0e2
            and RFC 3066 (Revised version of RFC 1766).
          </xs:documentation> 
        </xs:annotation> 
      </xs:pattern> 
    </xs:restriction> 
  </xs:simpleType>
Run Code Online (Sandbox Code Playgroud)

然后模式是:

[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*
Run Code Online (Sandbox Code Playgroud)

  • 如果添加线锚和非捕获组,则变为`^[a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*$` (3认同)