简体   繁体   中英

Get all characters not matching the Reg expression Pattern in Javascript

I have below requirement where a entered text must match any of below allowed character list and get all characters not matching the reg exp pattern.

  1. 0-9
  2. AZ,az

And special characters like:

  1. space,.@,-_&()'/*=:;
  2. carriage return
  3. end of line

The regular expression which I could construct is as below

/[^a-zA-Z0-9\ \.@\,\r\n*=:;\-_\&()\'\/]/g

For an given example, say input='123.@&-_()/*=:/\\';#$%^"~!?[]av' . The invalid characters are '#$%^"~!?[]' .

Below is the approach I followed to get the not matched characters.

1) Construct the negation of allowed reg expn pattern like below.

/^([a-zA-Z0-9\\ \\.@\\,\\r\\n*=:;\\-_\\&()\\'\\/])/g (please correct if this reg exp is right?)

2) Use replace function to get all characters

var nomatch = '';        
for (var index = 0; index < input.length; index++) {
    nomatch += input[index].replace(/^([a-zA-Z0-9\ \.@\,\r\n*=:;\-_\&()\'\/])/g, '');
}

so nomatch='#$%^"~!?[]' // finally

But here the replace function always returns a single not matched character. so using a loop to get all. If the input is of 100 characters then it loops 100 times and is unnecessary.

Is there any better approach get all characters not matching reg exp pattern in below lines.

  1. A better regular expression to get not allowed characters(than the negation of reg exp I have used above)?
  2. Avoid unnecessary looping?
  3. A single line approach?

Great Thanks for any help on this.

You can simplify it by using reverse regex and replace all allowed characters by empty string so that output will have only not-allowed characters left.:

 var re = /[\\w .@,\\r\\n*=:;&()'\\/-]+/g var input = '123.@&-_()/*=:/\\';#$%^"~!?[]av' var input = input.replace(re, '') console.log(input); //=> "#$%^"~!?[]" 

Also note that many special characters don't need to be escaped inside a character class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM