0

I want a regular expression to test a string that meets the following requirements:

  • It may contain a-z A-Z and 0-9
  • It may contain - and _ but may not start nor end with these characters
  • It may also contain a space but may not start nor end with it

It should match the following strings:

  • folder_with some-content
  • folderwithcontent
  • folder_with_content
  • folder-with content

Could someone please help me with it? Thanks in advance!

Marc
  • 412
  • 4
  • 17

1 Answers1

3

You have your pieces, so put them together:

/^[a-z0-9](?:[a-z0-9_ -]*[a-z0-9])?$/i

This does exactly what you're looking for. The only complicated part is allowing a single character.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592