Removing non-alphanumeric chars
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
input.replace(/\W/g, '')
Note that \W is the equivalent of [^0-9a-zA-Z_] - it includes the underscore character. To also remove underscores use e.g.:
input.replace(/[^0-9a-z]/gi, '')
The input is malformed
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
A backslash in the string needs escaping if it's to be taken literally:
"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output
Handling malformed strings
If you're not able to escape the input string correctly (why not?), or it's coming from some kind of untrusted/misconfigured source - you can do something like this:
JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""
But they are also removed by the replacement regex.
Answer from AD7six on Stack Overflowjavascript - Remove not alphanumeric characters from string
How can I remove all NON alphabetic characters from my list of strings [PYTHON]
Something like that is perfect for regular expressions. re.sub takes as input a regular expression that defines what to match, a string (or a function) to decide what to replace what is matched with, and a string to do all this matching and replacing on. As an example:
import re string = "lincoln's silly flat dishwatery utterances chicago times 1863" print re.sub(r'[^a-zA-Z ]', '', string).split() # ouputs: # ['lincolns', 'silly', 'flat', 'dishwatery', 'utterances', 'chicago', 'times']
This will replace all characters that are not between lowercase a-z, uppercase A-Z, or a space, with nothing -- essentially removing them.
More on reddit.comc# - How do I remove all non alphanumeric characters from a string except dash? - Stack Overflow
Stripping everything but alphanumeric chars from a string in Python - Stack Overflow
Removing non-alphanumeric chars
The following is the/a correct regex to strip non-alphanumeric chars from an input string:
input.replace(/\W/g, '')
Note that \W is the equivalent of [^0-9a-zA-Z_] - it includes the underscore character. To also remove underscores use e.g.:
input.replace(/[^0-9a-z]/gi, '')
The input is malformed
Since the test string contains various escaped chars, which are not alphanumeric, it will remove them.
A backslash in the string needs escaping if it's to be taken literally:
"\\test\\red\\bob\\fred\\new".replace(/\W/g, '')
"testredbobfrednew" // output
Handling malformed strings
If you're not able to escape the input string correctly (why not?), or it's coming from some kind of untrusted/misconfigured source - you can do something like this:
JSON.stringify("\\test\red\bob\fred\new").replace(/\W/g, '')
"testredbobfrednew" // output
Note that the json representation of a string includes the quotes:
JSON.stringify("\\test\red\bob\fred\new")
""\\test\red\bob\fred\new""
But they are also removed by the replacement regex.
All of the current answers still have quirks, the best thing I could come up with was:
string.replace(/[^A-Za-z0-9]/g, '');
Here's an example that captures every key I could find on the keyboard:
var string = '123abcABC-_*(!@#$%^&*()_-={}[]:\"<>,.?/~`';
var stripped = string.replace(/[^A-Za-z0-9]/g, '');
console.log(stripped);
Outputs: '123abcABC'.
FYI I do want to keep the commas between strings in the list. Here is my code right now. I've been working on this for hours and I'm stuck, I can't figure it out. I working on a program that will append every string of at least four characters to a new list. I'm going to use this to run through some ebooks I have in .txt
def parse(s):
listOfWords = []
i = 0
final = s.lower()
final = final.split()
while i < len(final):
if len(final[i]) >= 4:
listOfWords.append(final[i])
i = i + 1
return listOfWordsCurrent Output
['lincoln’s', 'silly,', 'flat', 'dishwatery', 'utterances', 'chicago', 'times,', '1863']
Desired Output
["lincoln", "silly", "flat", "dishwatery", "utterances", "chicago", "times"]
Something like that is perfect for regular expressions. re.sub takes as input a regular expression that defines what to match, a string (or a function) to decide what to replace what is matched with, and a string to do all this matching and replacing on. As an example:
import re
string = "lincoln's silly flat dishwatery utterances chicago times 1863"
print re.sub(r'[^a-zA-Z ]', '', string).split()
# ouputs:
# ['lincolns', 'silly', 'flat', 'dishwatery', 'utterances', 'chicago', 'times']
This will replace all characters that are not between lowercase a-z, uppercase A-Z, or a space, with nothing -- essentially removing them.
Use isAlpha() on each character.
Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
1 Comment by ShawnFeatherly
I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string string.printable (part of the built-in string module). The use of compiled '[\W_]+' and pattern.sub('', str) was found to be fastest.
$ python -m timeit -s \
"import string" \
"''.join(ch for ch in string.printable if ch.isalnum())"
10000 loops, best of 3: 57.6 usec per loop
$ python -m timeit -s \
"import string" \
"filter(str.isalnum, string.printable)"
10000 loops, best of 3: 37.9 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]+', '', string.printable)"
100000 loops, best of 3: 15 usec per loop
$ python -m timeit -s \
"import re, string; pattern = re.compile('[\W_]+')" \
"pattern.sub('', string.printable)"
100000 loops, best of 3: 11.2 usec per loop
Regular expressions to the rescue:
import re
re.sub(r'\W+', '', your_string)
By Python definition
'\W==[^a-zA-Z0-9_], which excludes allnumbers,lettersand_