Regular expression to exclude dashes and underscores as the last character

I need a regex to check the conditions below,

1) include - (dash)  and _ (underscore) as valid components. 
2) cannot end with (dash) and (underscore).

Im using this - ^[A-Za-z0-9]+([-_]+[A-Za-z0-9]+)*$but not sure how to include the second condition, i.e. can't end with a dash or underline

+1
source share
2 answers

Use the following:

^.*[^-_]$

This allows any sequence of characters from the beginning ( ^.*) to ( $) any character that is not a dash or underscore ( [^-_]). If your actual characters without end are only alphabetic letters plus -_, then .*use instead [A-Za-z0-9-_]*.

+2

:

^[^-_].*[^-_]$

- _= ^[^-_], - _= [^-_]$

0

Source: https://habr.com/ru/post/1525273/


All Articles