6

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. A-Z,a-z

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.

2
  • Do you want a string (or an array) without duplicates? Commented Jun 19, 2017 at 12:12
  • Use an online tool like regex101 to check your regex. Commented Jun 19, 2017 at 12:21

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"Also note that many special characters don't need to be escaped inside a character class." just make sure if you have a - (hyphen) character to match to put that as the last character in the class. Otherwise it will try to range the characters around it. :)
True, that's why I moved - to the end of character class in my answer :)
@anubhava it worked for me. Apologies for late response and great thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.