How to separate symbols from text with regex?

by muriel.schmidt , in category: Third Party Scripts , 15 days ago

How to separate symbols from text with regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 14 days ago

@muriel.schmidt 

To separate symbols from text using regular expressions (regex), you can create a pattern that matches any non-alphanumeric characters. Here is an example in Python:

1
2
3
4
5
6
7
8
import re

text = "Hello, 123 world!"
symbols_pattern = re.compile("[^ws]+")

symbols = symbols_pattern.findall(text)

print(symbols)


This code will output a list of symbols present in the text, in this case, the comma and exclamation mark:

1
[',', '!']


The regex pattern [^ws]+ matches any characters that are not alphanumeric (w) or whitespace (s). You can customize the regex pattern based on the specific symbols you want to separate from the text.