K2902
K2902

Reputation: 53

How to construct a regex for filenames to not have special characters and limited length?

I am looking for a regular expression to make sure that my filenames do not contain special characters and are limited to length 9.

I am using ^[a-zA-Z0-9][a-zA-Z0-9 ]{0,9}[a-zA-Z0-9]$ but it’s not able to match a single character like “a”.

Upvotes: 2

Views: 36

Answers (1)

Steve Chambers
Steve Chambers

Reputation: 39444

The part after the first character can be made optional by surrounding it with parentheses () and then appending a question mark ?. To not include this as a capturing group, use ?: after the opening bracket:

^[a-zA-Z0-9](?:[a-zA-Z0-9 ]{0,9}[a-zA-Z0-9])?$

Upvotes: 2

Related Questions