我最近需要这个,所以我创建了一个完全遵循RFC-2253 的 LDAPv3 专有名称语法的。
属性类型
attributeType 可以用两种方式表示。以 alpha 开头的字母数字字符串,使用以下方法验证:
[A-Za-z][\w-]*
或者它可以是一个 OID,使用以下方法验证:
\d+(?:\.\d+)*
所以 attributeType 验证使用:
[A-Za-z][\w-]*|\d+(?:\.\d+)*
属性值
一个attributeValue 可以用3 种方式表示。一个十六进制字符串,它是一个以 # 开头的十六进制对序列。十六进制字符串验证使用:
#(?:[\dA-Fa-f]{2})+
或转义字符串;每个非特殊字符都“按原样”表示(使用[^,=\+<>#;\\"] 验证)。特殊字符可以用前导 \ 表示(使用 \\[,=\+<>#;\\"] 验证)。最后,任何字符都可以表示为带有前导 \ 的十六进制对(使用 \\[\dA-Fa-f]{2} 验证)。转义字符串验证使用:
(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*
或者一个带引号的字符串;该值以" 开头和结尾,并且可以包含除\ 和" 之外的任何未转义字符。此外,可以使用上述转义字符串中的任何方法。引用字符串验证使用:
"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*"
所有组合,attributeValue 验证使用:
#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*"
名称组件
BNF 中的名称组件是:
name-component = attributeTypeAndValue *("+" attributeTypeAndValue)
attributeTypeAndValue = attributeType "=" attributeValue
在正则表达式中是:
(?#attributeType)=(?#attributeValue)(?:\+(?#attributeType)=(?#attributeValue))*
用上面的值替换 (?#attributeType) 和 (?#attributeValue) 占位符给我们:
(?:[A-Za-z][\w-]*|\d+(?:\.\d+)*)=(?:#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*")(?:\+(?:[A-Za-z][\w-]*|\d+(?:\.\d+)*)=(?:#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*"))*
验证单个名称组件。
专有名称
最后,专有名称的 BNF 是:
name-component *("," name-component)
在正则表达式中是:
(?#name-component)(?:,(?#name-component))*
用上面的值替换 (?#name-component) 占位符给我们:
^(?:[A-Za-z][\w-]*|\d+(?:\.\d+)*)=(?:#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*")(?:\+(?:[A-Za-z][\w-]*|\d+(?:\.\d+)*)=(?:#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*"))*(?:,(?:[A-Za-z][\w-]*|\d+(?:\.\d+)*)=(?:#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*")(?:\+(?:[A-Za-z][\w-]*|\d+(?:\.\d+)*)=(?:#(?:[\dA-Fa-f]{2})+|(?:[^,=\+<>#;\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*|"(?:[^\\"]|\\[,=\+<>#;\\"]|\\[\dA-Fa-f]{2})*"))*)*$
Test it here