-2

I need to make regex for java language which :

  1. does not ends or starts with space
  2. contains latin letters
  3. contains numbers
  4. contains «–», «_», «,», «.», «(», «)», «\», «/» ,« »(space)
  5. lenght from 1 to 255 I have tried:
^[^\s][a-zA-Z0-9-_,. ()\\\/]+[^\s]$ 
^[a-zA-Z0-9\\-_,. ()\\\\/][a-zA-Z0-9\\-_,. ()\\\\/ ]{0,253}[a-zA-Z0-9\\-_,. ()\\\\/]$

but they does not matches strinds with one char like "a" or "/" Also i know that i cant pass into my api in json like : "test" : "" because it throws exception that json is invalid, so i tried "\" but id does not matches. Help me plese !

  • To support single char strings, just make ``[a-zA-Z0-9\\-_,. ()\\\\/ ]{0,253}[a-zA-Z0-9\\-_,. ()\\\\/]`` optional. I.e. ``^[a-zA-Z0-9\\-_,. ()\\\\/](?:[a-zA-Z0-9\\-_,. ()\\\\/ ]{0,253}[a-zA-Z0-9\\-_,. ()\\\\/])?$`` – Wiktor Stribiżew Aug 24 '23 at 10:34
  • Or, using the first regex with lookarounds and a limiting quantifier: ``^(?!\\s)[a-zA-Z0-9\\-_,. ()\\\\/]{1,255}$(?<!\\s)`` – Wiktor Stribiżew Aug 24 '23 at 10:35
  • 1
    If your requirement is that the string must contain at least one letter, and at least one number, and at least one punctuation character, a single regular expression is a poor choice. A few lines of code will be dramatically easier to write and easier for other developers to read. – VGR Aug 24 '23 at 13:36

0 Answers0