-2

I am trying to build a regular expression with this criteria:

  • Not start or end with these characters '-', '.', '_'
  • The string must be between 4 to 8 length

Example of allowed strings:

  • hello
  • hellowor
  • he_ll_ow
  • he-ll.ow

Not allowed strings:

  • -hello
  • _hello
  • .hello
  • hello_
  • toolongstringhere
  • t

Currently, I have this expression:

Pattern.compile("^[^-_\\.](.*[^-_\\.])?$");

This is working for the allowed characters but when I tried to add the length the expression does not work anymore for the rule of the not allowed expressions at the end.

coding
  • 917
  • 2
  • 12
  • 25
  • Does this answer your question? [Regex to match words of a certain length](https://stackoverflow.com/questions/9043820/regex-to-match-words-of-a-certain-length) – gre_gor Feb 09 '23 at 01:30
  • Do you also want to match `a b c d` ? `^[^\s._-]\S{2,6}[^\s._-]$` Note that `hellowor` is under the allowed strings section. See https://regex101.com/r/tni9rn/1 – The fourth bird Feb 09 '23 at 09:42

2 Answers2

3

After matching the first and last character, the length of the string in between must be 2-6 characters.

^[^._-].{2,6}[^._-]$
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • but this example: hellowor -> (length 8) is passing when it should not match because the length – coding Feb 09 '23 at 01:18
  • 2
    @coding That's 4-8 characters though. Or did you mean 4 to 7 characters? – Unmitigated Feb 09 '23 at 01:23
  • 2
    @coding Your question specifically lists `hellowor` as an allowed string. And even if you really meant 4 to 7, instead of 4 to 8, this answer has told you what you need to know. I'm sure you can manage to subtract 1 from the 6 in the answer, without too much further help. – Dawood ibn Kareem Feb 09 '23 at 01:24
  • Thank you, why if I just add "^[^-_\\.](.*[^-_\\.])?.{4,8}$" does not work? How can I know where I should set the string length – coding Feb 09 '23 at 18:12
-3

Use this regex:

^[^-.、_][\\w-.、_]{2,6}[^-.、_]$

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • Without some text that explains what your regex does and how it fixes the problem, it is just noise, which is why you're getting downvoted and risk having the answer deleted., I'd suggest you review the [help] pages to learn how to properly write an answer and then edit yours here, or just delete it yourself. – Ken White Feb 09 '23 at 01:53