I want to ignore square brackets when using javascript regex

前端 未结 4 1358
我在风中等你
我在风中等你 2021-01-13 13:08

I am using javascript regex to do some data validation and specify the characters that i want to accept (I want to accept any alphanumeric characters, spaces and the followi

相关标签:
4条回答
  • 2021-01-13 13:44

    Try this: var pattern = /[^\w"!&,'\\-]/;

    Note: \w also includes _, so if you want to avoid that then try

    var pattern = /[^a-z0-9"!&,'\\-]/i;
    

    I think the issue with your regex is that A-z is being understood as all characters between 0x41 (65) and 0x7A (122), which included the characters []^_` that are between A-Z and a-z. (Z is 0x5A (90) and a is 0x61 (97), which means the preceding characters take up 0x5B thru 0x60).

    0 讨论(0)
  • 2021-01-13 13:49

    I'm not sure what you want but I don't think your current regexp does what you think it does:

    It tries to find one character is not A-z0-9 "!&,'\- (^ means not).

    Also, I'm not even sure what A-z matches. It's either a-z or A-Z.

    So your current regexp matches strings like "." and "Hi." but not "Hi"

    0 讨论(0)
  • 2021-01-13 13:51

    The reason is that you are using A-z rather than A-Za-z. The ascii range between Z (0x5a) and a (0x61) includes the square brackets, the caret, backquote, and underscore.

    0 讨论(0)
  • 2021-01-13 14:04

    Your regex is not in line with what you said:

    I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed

    If you want to accept only those characters, you need to remove the caret:

    var pattern = /^[A-Za-z0-9 "!&,'\\-]+$/;
    

    Notes:

    1. A-z also includesthe characters:

      [\]^_`
      .

      Use A-Za-z or use the i modifier to match only alphabets:

       var pattern = /^[a-z0-9 "!&,'\\-]+$/i;
      
    2. \- is only the character -, because the backslash will act as special character for escaping. Use \\ to allow a backslash.

    3. ^ and $ are anchors, used to match the beginning and end of the string. This ensures that the whole string is matched against the regex.

    4. + is used after the character class to match more than one character.


    If you mean that you want to match characters other than the ones you accept and are using this to prevent the user from entering 'forbidden' characters, then the first note above describes your issue. Use A-Za-z instead of A-z (the second note is also relevant).

    0 讨论(0)
提交回复
热议问题