user11537130
user11537130

Reputation: 296

Regex Pattern for not allowing slash on beginning and ending and not allowing special characters except slash, underscore, space

I have a requirement with this list

  1. No slash(/), underscore(_), and spaces( ) at the beginning and ending.
  2. Alphanumeric with spaces, underscore, slash in between of string are allowed.
  3. All special characters are not allowed except slash(/), underscore(_), and spaces( ).

test - (incorrect) space at the end test - (correct) no space at the end test - (incorrect) space at the beginning 54test/ - (incorrect) / at the end /54test - (incorrect) / at the beginning 54test/one - (correct) 54test one/my - (correct) 54test /my - (incorrect)

Here's my current regex but I can't really expand it because I'm pretty new with regex. and I Just get this at some post in SO

^[a-z0-9](?!.*?[^\na-z0-9]{2}).*?[a-z0-9]$

Upvotes: 1

Views: 753

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

^[a-zA-Z0-9]+(?:[_\/ ][a-zA-Z0-9]+)*$

See regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string
  • [a-zA-Z0-9]+ - 1+ alphanumeric chars
  • (?:[_\/ ][a-zA-Z0-9]+)* - 0 or more repetitions of _, / or space and then 1+ alphanumeric chars
  • $ - end of string

Upvotes: 1

Related Questions