Home > other >  Regex to prevent double underscores at the beginning and the end of the string
Regex to prevent double underscores at the beginning and the end of the string

Time:01-19

I currently have a regex to match a url subpath. It looks like this

^(?!^__.*__$).[a-zA-Z0-9_.-] $

I want to disable ONLY 2 underscores at the beginning and the end of the string because it's a reserved string. Any number of underscores other than 2 should be allowed

For example:

_should_work_
__should_work___
_should_work___
__should_not_work__

The problem now is even though I have more than 2 underscores, the regex will still not match

___should_work_but_doesnt__________

You can check out the regex here:

https://regex101.com/r/H9F1NN/1

CodePudding user response:

You can use

^(?!_(?!_))(?!(?:.*[^_])?_$)\w $

See the regex demo.

Details:

  • ^ - start of string
  • (?!_(?!_)) - the string should not start with a _ that is not immediately followed with another _ char
  • (?!(?:.*[^_])?_$) - the string can't end with a _ that is immediately preceded with a char other than a _ or at the start of string
  • \w - one or more letters, digit, or underscores
  • $ - end of string.

CodePudding user response:

You can do something like

^(?!^__[^_] (_[^_] )*__$).[a-zA-Z0-9_.-] $
^(?!^__[^_].*(?<!_)__$).[a-zA-Z0-9_.-] $

Where both [^_] (_[^_] )* and [^_].*(?<!_) match any string that does not start and end with an underscore.

  • Related