Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

I'm trying to create a Regex test in JavaScript that will test a string to contain any of these characters:

!$%^&*()_+|~-=`{}[]:";'<>?,./ 

More Info If You're Interested :)

It's for a pretty cool password change application I'm working on. In case you're interested here's the rest of the code.

I have a table that lists password requirements and as end-users types the new password, it will test an array of Regexes and place a checkmark in the corresponding table row if it... checks out :) I just need to add this one in place of the 4th item in the validation array.

var validate = function(password){     valid = true;      var validation = [         RegExp(/[a-z]/).test(password), RegExp(/[A-Z]/).test(password), RegExp(/\d/).test(password),          RegExp(/\W|_/).test(password), !RegExp(/\s/).test(password), !RegExp("12345678").test(password),          !RegExp($('#txtUsername').val()).test(password), !RegExp("cisco").test(password),          !RegExp(/([a-z]|[0-9])\1\1\1/).test(password), (password.length > 7)     ]      $.each(validation, function(i){         if(this)             $('.form table tr').eq(i+1).attr('class', 'check');         else{             $('.form table tr').eq(i+1).attr('class', '');             valid = false         }     });      return(valid);  } 

Yes, there's also corresponding server-side validation!

like image 710
pixelbobby Avatar asked Dec 02 '11 16:12

pixelbobby


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What regex matches any character?

Matching a Single Character Using Regex By default, the '. ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.


1 Answers

The regular expression for this is really simple. Just use a character class. The hyphen is a special character in character classes, so it needs to be first:

/[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]/ 

You also need to escape the other regular expression metacharacters.

Edit: The hyphen is special because it can be used to represent a range of characters. This same character class can be simplified with ranges to this:

/[$-/:-?{-~!"^_`\[\]]/ 

There are three ranges. '$' to '/', ':' to '?', and '{' to '~'. the last string of characters can't be represented more simply with a range: !"^_`[].

Use an ACSII table to find ranges for character classes.

like image 152
Jeff Hillman Avatar answered Sep 18 '22 13:09

Jeff Hillman