开发者

Regular expression for DN addresses

How to write a regular expression in javascript that must follow the conditions

  1. All segment in the DN address should follow the sequenc开发者_C百科e cn=<name>,ou=<name>,o=<bic8>,o=swift
  2. All segments should be separated with ,.
  3. The DN address should have maximum of 100 characters.
  4. No space is allowed.
  5. Minimum of 2 and maximum of 10 segments are allowed in a DN address.
  6. The <name> part must contain minimum of 2 characters and maximum 20 alphanumeric characters. The characters should be in lower case. Only one special character is allowed to be used i.e. -(Hypen).
  7. The DN address will have maximum 2 numbers. The <name> part can contain maximum of 2 numerical digits.

Thanks in advance


I think .split() is a lot easier to use in this case.

First split the entire string on the ,'s and then split every separate segment of the resulting array on the ='s.

Especially on a well defined spec as this, split is more then enough to handle it.


Untested code follows, don't blame me if it blows up your computer:

var parseDn(str)
  var m = /^cn=(.*?),ou=(.*?),o=(.*?),o=swift$/.exec(str);
  if (!m) { return null; } // (a) and (b).
  if (s.length > 100) { return null; } // (c).
  if (/\s/.exec(s)) { return null; } // (d).
  var x = {cn:m[1], ou:m[2], o:m[3]};
  var isValidName = function(s) { return (/^[a-z-]{2,20}$/).exec(s); }
  if (!isValidName(x.cn) || !isValidName(x.ou) || !isValidName(x.o)) {
    return null; // (f).
  }
  var countNumbers = function(s) { return s.replace(/\D/g, "").length; }
  if (countNumbers(x.cn)>2 || countNumbers(x.ou)>2 || countNumbers(x.o)>2) {
    return null; // (g).
  }
  return x; // => {"cn":"name", "ou":"name", "o":"bic8"}
}

Note that (e) and a few of the points regarding "segments" are completely unchecked since the description is vague. But this should get you started...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜