How do I write a regular expression that includes all keyboard characters except \'~\' and \',\'?
A related one.
I wasted a lot of time searching, so below is the answer I came up with.
I wanted all keyboard keys (including space and tab):
// all keys (including space and tab)
var allKeyboardKeysRegex = /^[a-zA-Z0-9~`!@#\$%\^&\*\(\)_\-\+={\[\}\]\|\\:;"'<,>\.\?\/ ]*$/;
// example tests
var nonShiftChars = "`1234567890-= qwertyuiop[]\asdfghjkl;'zxcvbnm,./ "
var shiftChars = "~!@#$%^&*()_+{}|:\"<>? ";
var someAlphaNumeric = "aAbB12 89yYzZ";
// test with allKeyboardKeysRegex
allKeyboardKeysRegex.test(nonShiftChars);
allKeyboardKeysRegex.test(shiftChars);
allKeyboardKeysRegex.test(someAlphaNumeric);
Output:
true
true
true
if you want to exclude some characters, then just delete them from above 1st line regex line (allKeyboardKeysRegex).
Example:
// removing '~' and ','
var allKeyboardKeysRegexMinusSome = /^[a-zA-Z0-9`!@#\$%\^&\*\(\)_\-\+={\[\}\]\|\\:;"'<>\.\?\/ ]*$/;
Hope that will help someone.
Update
List of all chars
"1234567890"
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"~`!@#$%^&*()_-+={[}]|\:;"'<,>.?/ " (last 2 are space & tab here)
"~`!@#$%^&*()_-+={[}]|\\:;\"'<,>.?/ \t\r\n " (last 2 are space & tab here, all these chars are escaped with \)
This worked for me:
[A-Za-z0-9-]+[ 0-9A-Za-z#$%=@!{},`~&*()'<>?.:;_|^/+\t\r\n\[\]"-]*
Have you tried this?
[^~,]
Now to exclude characters not in keyboard, I believe you have to include them all.
[a-zA-Z0-9\t\n ./<>?;:"'`!@#$%^&*()\[\]{}_+=|\\-]
Which pretty much covers it (even though it looks like a crazy way to get things done). Maybe the problem definition can help you add more stuffs to exclude in the first list [^~,]
than try to create a huge list of all keyboard chars.
You didn't say what language/tool you're using, but in Java I would go with this regex:
"[\\p{Print}&&[^~,]]"
That's the intersection of two sets: all printing ASCII characters, and all characters that aren't a tilde or a comma.
I had to do this for regex to work:
"[^~,][^~,]*"
because [^~,]
negates ~
and ,
[^~,]*
means in zero or many copies of ~
and ,
(that is useless for our case)
and by putting [^~,][^~,]*
gets you to negate one or more copy of ~
or ,
Reg-Ex for all supported key board chars worked for me :
/^[a-zA-Z0-9.!@?#"$%&:';()*\+,\/;\-=[\\\]\^_{|}<>~` ]+$/
To except '~' and ',' chars :
/^[a-zA-Z0-9.!@?#"$%&:';()*\+\/;\-=[\\\]\^_{|}<>` ]+$/