'I want to write regex that starts and end with numbers and letters only but can have special character hyphen, underscore and space in between

I tried writing this: ^[A-Za-z0-9-][A-Za-z0-9- ]{1,30}$ But the regex should not start and end with a special character or space.

Sample values It should allow:

EcoLight

Eco-Light

Eco_Light

Eco Light

Eco Light 1



Solution 1:[1]

If the regex pattern ends with a letter or digit then it won't end with something else

^[A-Za-z0-9-][A-Za-z0-9_ -]{0,29}[A-Za-z0-9]$

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LukStorms