This can be done without regex:
>>> string = "Special $#! characters spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'
You can use str.isalnum:
S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
If you insist on using regex, other solutions will do fine. However note that if it can be done without using a regular expression, that's the best way to go about it.
Answer from user225312 on Stack OverflowThis can be done without regex:
>>> string = "Special $#! characters spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'
You can use str.isalnum:
S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
If you insist on using regex, other solutions will do fine. However note that if it can be done without using a regular expression, that's the best way to go about it.
Here is a regex to match a string of characters that are not a letters or numbers:
[^A-Za-z0-9]+
Here is the Python command to do a regex substitution:
re.sub('[^A-Za-z0-9]+', '', mystring)
How do I remove remove stuff like (. , ' *) from a string?
machine learning - remove special character in a List or String - Data Science Stack Exchange
delete all special characters at start and end of string
Powershell - Remove all characters except...
I have a string:
"Bob 'hit' a ball, the hit BALL flew far after it was hit."
And I want to replace the word 'hit' by 'sample'.
How do I do that when the word gets immediately followed/preceded by stuff like (. , ' *)
Edit: I know using replace() will work but I don't know what special characters there will be in the string. Some strings had characters like ( - [ / + .
Regular expressions can be used to create a simple tokenizer and normalizer:
from __future__ import annotations
import re
def tokens(text: str) -> list(str):
"List all the word tokens in a text."
return re.findall('[\w]+', text.lower())
assert tokens("To be, or not to be, that is the question:") == ['to', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'the', 'question']
Otherwise, use an established library like spaCy to generate a list of tokens.
This can be achieved by Regular Expresiions
import re
modified_string = re.sub(r'\W+', '', input_string) # on individual tokens
modified_string = re.sub(r'[^a-zA-Z0-9_\s]+', '', input_string) # on sentence itself.Here I have modified RegEx to include spaces as well
'\W == [^a-zA-Z0-9_], so everything except numbers,alphabets and _ would be replaced by space