tags:

views:

64

answers:

5

Hi, Can anybody help me writting a regular expression to replace these characters with a empty string. Character list is given below.

public static char[] delimiters = { ' ', '\r', '\n', '?', '!', ';', '.', ',', '`', ':', '(', ')', '{', '}', '[', ']', '|', '\'', '\\', '~', '=', '@', '>', '<', '&', '%', '-', '/', '#' };

Thanks. Subrat.

+2  A: 
var in = "...";
var out = in.replace(/[ \r\n?!:;\-(){}\[\]\\'"=@><&%\/#]+/g, '');

I may have missed a couple of characters.

An alternative solution may be to take a white list rather than black list approach:

var out = in.replace(/[^\w]+/g, '');

This will remove anything that isn't a word character, meaning a letter (uppercase or lowercase), digit or underscore.

cletus
This is not working. I tried , it can't give the replaced string. anyways thanks for the effort
Subrat
I want to replace only those characters (strictly) mentioned in the list.
Subrat
+1  A: 

Try this:

var delimiters = [' ', '\r', '\n', '?', '!', ';', '.', ',', '`', ':', '(', ')', '{', '}', '[', ']', '|', '\'', '\\', '~', '=', '@', '>', '<', '&', '%', '-', '/', '#'],
    re = new RegExp("[" + delimiters.join("").replace(/[-\\\]]/g, "\\$&") + "]", "g");
str = str.replace(re, "");
Gumbo
A: 

This might be too aggressive.

/[^A-z0-9]/g
Greg K
I want to replace only those characters (strictly) mentioned in the list.
Subrat
OK, in which case don't use the above.
Greg K
+1  A: 

In your case, I would write a function that escapes any character that could have a special meaning in a regexp, applies the regexp and returns the result:

String.prototype.exclude = function(blacklist) {
    for(var i=0; i<blacklist.length; i++) {
        if(blacklist[i].match(/\W/)) {
            blacklist[i] = '\\'+blacklist[i];
        }
    }
    return this.replace(new RegExp('['+blacklist.join('')+']', 'g'), '');
};

var myString = "j a\nv\ra?s!c;r.i,p`t:I(s)A{w}e[s]o|m'e\\~=@><&%-/#"; 

myString.exclude([' ', '\r', '\n', '?', '!', ';', '.', ',', '`', ':', '(', ')', '{', '}', '[', ']', '|', '\'', '\\', '~', '=', '@', '>', '<', '&', '%', '-', '/', '#']);

// returns "JavascriptIsAwesome" which is of course the correct answer
Alsciende
+1  A: 

Here's the regex you want:

var re = /[ \r\n?!;.,`:(){}\[\]\|\'\\~=@><&%-\/#]/g;

For example:

var test = "j a\nv\ra?s!c;r.i,p`t:I(s)A{w}e[s]o|m'e\\~=@><&%-/#";
test.replace(re, '')

>>> "javascriptIsAwesome"

FYI, the general notation for this sort of thing in regular expressions is "/[...]/" - means, "match any character inside the brackets"

broofa