Find non-alphanumeric characters with alphanumeric character anywhere before

Viewed 293

So I was writing some code, that would take a String, like "This$#is% Matrix# %!" and delete all non-alphanumeric symbols, that have alphanumeric symbols somewhere on both surrounding them. I managed to get that, but the problem comes with Strings, that have non-alphanumeric symbols before any other symbols. I wanted to do it with a "non fixed lenght" lookback, but that is not possible. Are there any workarounds? Code and some examples:

decodedString = re.sub(r"[^0-9,a-z,A-Z](?=.+[0-9,a-z,A-Z])", " ",decodedString)
print("1st regex: " + decodedString)
decodedString = re.sub(r" (?= .+[0-9,a-z,A-Z])", "", decodedString)
print("2nd regex: " + decodedString)

(The second regex deletes spaces, that are twice in a row, but it should also only delete if an alphanumeric character is before it).

"# @i##U" should become "# @i U", this one is the only one not working, because it deletes the non-alphanumeric characters at the start (it gives back "i #U")

"This%%is$Matrix%%$script" should become "This is Matrix script"

"This$#is% Matrix# %!" should become "This is Matrix# %!"

Help would be much appreciated!

1 Answers

You can use

re.sub(r'(?<=[^\W_])[\W_]+(?=[^\W_])', ' ', text)

Details:

  • (?<=[^\W_]) - a letter or digit should be immediately on the left
  • [\W_]+ - one or more non-alphanumeric
  • (?=[^\W_]) - a letter or digit should be immediately on the right.

See the regex demo.

See the Python demo:

import re
texts = ['This%%is$Matrix%%$script', 'This$#is% Matrix# %!']
for text in texts:
    print(re.sub(r'(?<=[^\W_])[\W_]+(?=[^\W_])', ' ', text))

Output:

This is Matrix script
This is Matrix# %!
Related