Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression with "not character" not matches as expected

Tags:

regex

I am trying to satisfy next restrictions:

  1. line has from 3 to 256 chars that are a-z, 0-9, dash - or dot .
  2. this line cannot start or end with -

I want to get kind of next output:

aaa  -> good
aaaa -> good
-aaa -> bad
aaa- -> bad
---a -> bad

A have some of regexes that don't give right answer: 1) ^[^-][a-z0-9\-.]{3,256}[^-]$ gives all test lines as bad;

2) ^[^-]+[a-z0-9\-.]{3,256}[^-]+$ treats first three lines as one matching string since [^-] matches new line I guess.

3) ^[^-]?[a-z0-9\-.]{3,256}[^-]?$ (? for one or zero matching dash) gives all test lines as good

Where is the truth? I'm sensing it's either close to mine or much more complicated.

P.S. I use python 3 re module.

like image 262
While True Avatar asked Feb 08 '23 07:02

While True


1 Answers

This one is almost correct: ^[^-][a-z0-9\-.]{3,256}[^-]$

The [^-] at the start and end represent one character already, so you will need to change {3,256} into {1,254}

Also, you probably only want a-z, 0-9 and . at the start and end (not just anything except -), so the full regex becomes:

^[a-z0-9.][a-z0-9\-.]{1,254}[a-z0-9.]$
like image 107
Manu Avatar answered Feb 20 '23 16:02

Manu