Home > Enterprise >  Regex for limiting characters
Regex for limiting characters

Time:10-26

I need a regex in which -

  1. No lowercase letters
  2. No leading or trailing whitespace
  3. Length should be less than or equal to 18

I tried

^[^\s][A-Z0-9\W]{0,18}

CodePudding user response:

You can use

\A(?!\s)[^a-z]{0,18}\z(?<!\s)

In Java, you can define it as

bool valid = text.matches("\\A(?!\\s)[^a-z]{0,18}\\z(?<!\\s)");

See the regex demo (adapted for testing against a single multiline text).

Details:

  • \A - start of string
  • (?!\s) - no whitespace allowed right after
  • [^a-z]{0,18} - zero to eighteen occurrences of any chars other than lowercase ASCII letters (replace [^a-z] with \P{Ll} to match any chars other than Unicode lowercase letters)
  • \z(?<!\s) - end of string that has no whitespace immediately before it.

CodePudding user response:

You could start the match with a non whitespace char other than a-z

Then optionally match 0-16 chars other than a lowercase char followed by again a non whitespace char other than a-z.

^[^\sa-z](?:[^a-z\r\n]{0,16}[^\sa-z])?$

In Java

String regex = "^[^\\sa-z](?:[^a-z\\r\\n]{0,16}[^\\sa-z])?$";

Explanation

  • ^ Start of string
  • [^\sa-z] Match a non whitespace char other than a-z
  • (?: Non capture grup
    • [^a-z\r\n]{0,16} Match 0-16 chars other than a-z or a newline
    • [^\sa-z] Match a non whitespace char other than a-z
  • )? Close the non capture group and make it optional to also match a single character
  • $ End of string

See a regex demo and a Java demo

  • Related