Regular expression that includes all keyboard characters except '~' and ','

前端 未结 6 1178
余生分开走
余生分开走 2021-02-19 20:03

How do I write a regular expression that includes all keyboard characters except \'~\' and \',\'?

6条回答
  •  无人及你
    2021-02-19 20:47

    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 \)
    

提交回复
热议问题