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.
And special characters like:
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.
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.