Of course, here is a method that uses a small modification of the same regular expression, but with a short short code authoring.
^(?=(\D*\d)|)(?=([^az]*[az])|)(?=([^AZ]*[AZ])|)(?=([a-zA-Z0-9]*[^a-zA-Z0-9])|).{4,8}$
Here you have five capture groups - check to see if at least 3 of them are null. A null capture group effectively indicates that the alternative within the lookahead is mapped, and the capture group on the left cannot be mapped.
For example, in PHP:
preg_match("/^(?=(\\D*\\d)|)(?=([^az]*[az])|)(?=([^AZ]*[AZ])|)(?=([a-zA-Z0-9]*[^a-zA-Z0-9])|).{4,8}$/", $str, $matches); $count = -1; // Because the zero-eth element is never null. foreach ($matches as $element) { if ( !empty($element)) { $count += 1; } } if ($count >= 3) { // ... }
Or Java:
Matcher matcher = Pattern.compile(...).matcher(string); int count = 0; if (matcher.matches()) for (int i = 1; i < 5; i++) if (null != matcher.group(i)) count++; if (count >= 3)
source share