RegEx - Java - Matching Strings (012|123|234|345|456|567|678|789|890) -
i working on password enhancement , client wants password not have consecutive letters ie: 123, 234.
i have figured out can declare strings want match in regex (012|123|234|345|456|567|678|789|890)
, made regex sequence.
this sequence separated other sequences easy reading.
the problem is, cannot match password pattern if included 123 or 234 in password character.
i've read regex cannot detect 123 consecutive numbers, string, can so?
if have limited sequence of characters following 1 can use pattern
, .find()
on matcher on input , invert test:
// alternation needed, no need capture private static final pattern pattern = pattern.compile("012|123|234|345|456|567|678|789|890"); // ... if (pattern.matcher(input).find()) // fail: illegal sequence found
but if want detect code points follow 1 have use character functions:
final charbuffer buf = charbuffer.wrap(input); int maxsuccessive = 0; int successive = 0; char prev = buf.get(); char next; while (buf.hasremaining()) { next = buf.get(); if (next - prev == 1) successive++; else { maxsuccessive = math.max(maxsuccessive, successive); successive = 0; } prev = next; } // test maxsuccessive
note test successive characters according "canonical ordering", not collation. in locales, instance, after a
a
, not b
.
more generally, if want test password requirements , constraint evolves, better off splitting things bit. instance, consider this:
public interface passwordchecker { boolean isvalid(final string passwd); }
implement interface each of checks (for instance, length, presence/absence of characters, etc), , when check password, have list
of checkers; password invalid if 1 checker returns false:
private final list<passwordchecker> checkers = ...; // (final passwordchecker checker: checkers) if (!checker.isvalid(passwd)) return false; return true;
if use guava, can forget passwordchecker
, use predicate<string>
.
Comments
Post a Comment