Python Regex: why does this not work?

Why does this not work?

re.sub('\\b[a@](\\W|[a@])*[s5$](\\W|[s5$])*[s5$](\\W|[s5$])*($|\\W)', '*', '@ss')

I do not see why @ss is not replaced by *. Similarly, @55 is not replaced.

These are replaced: a55, a5s, as5, ass

Thank you!

Answers


It's because @ is not a word character, and thus the first \b is not matched.

This is my suggestion:

re.sub('(\\ba|@)(\\W|[a@])*[s5$](\\W|[s5$])*[s5$](\\W|[s5$])*($|\\W)', '*', '@ss')

(Replacing \b[a@] with (\ba|@))


You don't have a pair of parentheses around the first section. Try this:

re.sub('(\\b[a@])*(\\W|[a@])*[s5$](\\W|[s5$])*[s5$](\\W|[s5$])*($|\\W)', '*', '@ss')

If you're trying a sort of "profanity" check - I would take the logic out the regex.

look_alike = {'@': 'A', '$': 'S'}
test_string = ''.join(look_alike.get(c, c) for c in your_string.upper()) # also look at `string.translate`

Then if 'ASS' in test_string - or similar with word boundaries using an re.


Need Your Help

File permissions with FileSystemObject - CScript.exe says one thing, Classic ASP says another

asp-classic permissions wsh filesystemobject

I have a classic ASP page - written in JScript - that's using Scripting.FileSystemObject to save files to a network share - and it's not working. ("Permission denied")

Protractor - Firefox not reloading pages on browser.get(url)

firefox selenium-webdriver protractor

I'm writing some Protractor tests, but I'm running into trouble. When running the tests on Chrome, my tests all pass. When I run the tests on Firefox though, I see that the page is not re-loading b...