Spacing in between banned words - Regular Expression Python

Viewed 478

I am currently attempting to make a form of censor which will remove specific words. I am currently dealing with the idea that a user will be able to add spaces in between their letters and bypass the censor.

An example:

Banned word: Apple
Solution: A p p l e

Is there a way to combat this within Regex? My immediate thought is to use something akin to:

(a\s*p\s*p\s*l\s*e\s*)

However I feel like this is not an optimal solution.

If there is a solution to this, please do let me know. Thank you.

Edit:

Apples is not actually a banned word, just a placeholder for more crude words.

The idea of taking away white space and then comparing is not available, as some harmless words can be flagged this way. As an example:

"We need a medic, he's hit --> weneedamediche'[shit]" FLAGGED.
2 Answers

If your entry is a word with spaces, your regex works fine, however the strip method allows you to keep a record of the bad words and compare to them without generating regex for each bad word.

s = "A p p l e"
s = s.trim() 
print(is_badword(s))

If your entry is a text and your parsing it looking for bad words, then it becomes more difficult since I suppose you already rely on white spaces to get your tokens.

You would have to test every possible combinations of successive tokens. That is not achievable with a regex, but it should be manageable with a search tree for bad words in O(t^2) where t is the number of tokens. (Also I suppose users could also break the bad words other way than on each character, like Ap p le)

I hope this will be helpful.

sentence = 'learn to play with code'
sentence_to_word_list = sentence.split(' ') # spliting sentence to words here
banned_Words = ['to', 'with']   # list of banned words

for index, word in enumerate(sentence_to_word_list): # enumerate is used to track the index of each word
    if word in banned_Words:
        sentence_to_word_list[index] = '-'.join(list(word)) # we can join word here with any character,symbol or number

sentence = ' '.join(sentence_to_word_list) # again joining the list of word to make the whole sentence
print(sentence) # output : learn t-o play w-i-t-h code
Related