Q:

Avoid leading and trailing spaces on Alphanumeric string

I'm trying to validate the string to have only the followings

1.  Numbers (0-9) are valid
2.  Letters (A-Z, a-z) are valid
3.  No leading spaces are allowed
4.  No trailing spaces are allowed
5.  A space can be entered in the field text (outside of leading or trailing spaces)
6.  The following special characters are allowed:
    1.  Underscore (_)
    2.  Hyphen (-)
    3.  Comma (,)
    4.  Dot (.)

The following is working for me, except spaces
/^[A-Za-z0-9][A-Za-z0-9\_\.\-\,\s]*$/g
How to avoid leading spaces and trailing spaces with same Regex pattern?

A:

If there can be consecutive whitespaces characters in between, you could use an optional part where there second character class is repeated 0+ times ending with the same character class excluding \s
^[A-Za-z0-9](?:[A-Za-z0-9_.,\s-]*[A-Za-z0-9_.,-])?$

Regex demo
Or using \w to match word characters:
^[A-Za-z0-9](?:[\w.,\s-]*[\w.,-])?$

Note that \s could also possibly match a newline.

