Home > Software design >  Regex for strings containing at least 4 unique printable ASCII characters excluding few special char
Regex for strings containing at least 4 unique printable ASCII characters excluding few special char

Time:06-10

I am working on an application, in which input strings must have following properties:

  • Contains at least 4 unique characters
  • Doesn't contain non-printable ASCII characters
  • Doesn't contain comma (,), colon (:), equals sign (=), or space

I came up with below regex, which matches strings with at least 4 unique chars, and all printable ASCII chars excluding space.

^([!-~] )((?!\1)[!-~] )((?!\1|\2)[!-~] )((?!\1|\2|\3)[!-~] )$

How do I modify it to exclude comma (,), colon (:), equals sign (=)?

CodePudding user response:

In Java you can make use of Character Class Subtraction.

The range can look like [!-~&&[^,:=]]

^([!-~&&[^,:=]] )((?!\1)[!-~&&[^,:=]] )((?!\1|\2)[!-~&&[^,:=]] )((?!\1|\2|\3)[!-~&&[^,:=]] )$

In Java:

String regex = "^([!-~&&[^,:=]] )((?!\\1)[!-~&&[^,:=]] )((?!\\1|\\2)[!-~&&[^,:=]] )((?!\\1|\\2|\\3)[!-~&&[^,:=]] )$";

Regex demo

  • Related