Q:

How can I set limits to a regex? ( minimum and maximum length)

I am new to regex and want to verify a string which contains user password and that should contains lowercase, uppercase, number and special character and must have length of 8 characters and maximum of 20 so how how can I limit this regex between 8 and 20 characters here is the regex :
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$

A:

At the end of your regular expression you have the three symbols .+$
This means:

any character (.) 
one or more (+)
end of string ($). 

You want to target the one or more (+) and change it into a limit with {from, to} syntax. 
So for 8-20 chars use {8, 20} instead of +:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).{8,20}$

Do note that is is not good practice to limit password length.  Passwords should always be hashed and have a fixed length in the database.