user706838
user706838

Reputation: 5380

how to split at ALL special characters with re.split()

I am trying to split at any special character using re.split() from the import re package. This is what I have done so far, but doesn't really seem to work out yet. Any ideas?

word = [b for b in re.split(r'\`\-\=\~\!\@\#\$\%\^\&\*\(\)\_\+\[\]\{\}\;\'\\\:\"\|\<\,\.\/\>\<\>\?', a)]

Upvotes: 7

Views: 40546

Answers (3)

tobias_k
tobias_k

Reputation: 82929

Instead of enumerating all the "special" characters, it might be easier to create a class of characters where not to split and to reverse it using the ^ character.

For example, re.split(r"[^\w\s]", s) will split at any character that's not in either the class \w or \s ([a-zA-Z0-9_] and [ \t\n\r\f\v] respectively, see here for more info). However, note that the _ character is included in the \w class, so you might instead want to explicitly specify all the "regular" characters, e.g. re.split(r"[^a-zA-Z0-9\s]", s).

>>> re.split(r"[^a-zA-Z0-9\s]", "foo bar_blub23/x~y'z")
['foo bar', 'blub23', 'x', 'y', 'z']

Upvotes: 21

Maxime Lorant
Maxime Lorant

Reputation: 36181

You might want to split the string when you meet a character which isn't alphanumeric. For that, you can use the metacharacter \w in regex which means "every letter a-ZA-Z0-9" and match the opposite with ^ like this:

>>> re.split(r'[^\w]', 'toto"t"o/t!')
['toto', 't', 'o', 't', '']

Upvotes: 7

Toto
Toto

Reputation: 91488

Use a character class:

re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', a)

Upvotes: 11

Related Questions