This might be simple, but I have lost a ridiculous amount of hours trying to get there by myself. I need to have a regex that:
I spent hours on a regex builder and I can't get there. I know I can find a way for each of those criteria separately but I can't have them together.
I forgot to mention it must also only contain these characters [a-zA-Z0-9_-].
Try:
^(?![-_])(?:[a-zA-Z0-9]|[-_](?![-_]))+(?<![_-])$
See: regex101
Explanation
^
start of string from where...(?![-_])
not a -
or _
is follwing(?:
then a repetition of
[a-zA-Z0-9]
a character that can come at any time|
or[-_]
a -
or _
(?![-_])
as long as its not followed by another -
or _
)+
(?<![_-])$
with the last letter also not beeing -
or _