Regular expression for no more than two repeated letters/digits

前端 未结 5 1698
北恋
北恋 2020-12-03 07:23

I have a requirement to handle a regular expression for no more than two of the same letters/digits in an XSL file.

  • no space
  • does not support special
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 07:54

    In response to a clarification, it seems that a single regular expression isn't strictly required. In that case I suggest you use several regular expressions or functions. My guess is, performance isn't a requirement, since usually these sorts of checks are done in response to user input. User input validation can take 100ms and still appear to be instant, and you can run a lot of code in 100ms.

    For example, I personally would do a check for each of your conditions in a separate test. First, check for spaces. Second, check for at least one letter. Next, check for at least one number. Finally, look for any spans of three or more repeated characters.

    Your code will be much easier to understand, and it will be much easier to modify the rules later (which, experience has shown, is almost certainly going to happen).

    For example:

    function do_validation(string) {
        return (has_no_space(string) &&
                has_no_special_char(string) &&
                has_alpha(string) &&
                has_digit(string) &&
                ! (has_repeating(string)))
    

    I personally consider the above to be orders of magnitude easier to read than one complex regular expression. Plus, adding or removing a rule doesn't make you have to reimplement a complex regular expression (and thus, be required to re-test all possible combinations).

提交回复
热议问题