I need to use regex for some stuff (mentioned in code comments) and wrote the following code, which works perfectly fine for my need, but I wanted to know if there was a way to improve this code?
Am I using re.compile correctly in this case?
import re def regex(utterance): utterance = utterance.lower() # Replacing non ASCII characters with space message_ascii = re.compile(r'[^\x00-\x7F]+') message_ascii = message_ascii.sub(r' ', utterance) # If comma after number, replace comma with space message_comma_no = re.compile(r'(?<=[0-9]),') message_comma_no = message_comma_no.sub(r' ',message_ascii) # If comma after words, add space before and after message_comma_word = re.compile(r'(?<=[a-z]),') message_comma_word = message_comma_word.sub(r' , ',message_comma_no) # If "Dot and space" after word or number put space before and after message_dot = re.compile(r'(?<=[a-z0-9])[.] ') message_dot = message_dot.sub(r' . ',message_comma_word) # If any other punctuation found after word or number put space before and after message_punct = re.compile(r"(?<=[a-zA-Z0-9])(?=[?;!()'\"])|(?<=[?;!()'\"])(?=[a-zA-Z0-9])") message_punct = message_punct.sub(r' ', message_dot) # Remove Excess whitespaces message = ' '.join(message_punct.split()) return message