regexregex-lookaroundsregex-groupregex-negation

Regex for string that do not start with any character of a group and do not contain any of multiple substring


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:

  1. Do not start with '_' or '-'.
  2. Do not end with '_' or '-'.
  3. Do not contain '__' or '--' or '_-' or '-_'.

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.

Update

I forgot to mention it must also only contain these characters [a-zA-Z0-9_-].


Solution

  • Try:

    ^(?![-_])(?:[a-zA-Z0-9]|[-_](?![-_]))+(?<![_-])$
    

    See: regex101


    Explanation