Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all special character in a string except dot and comma

Tags:

java

android

I have a sentence with many special characters and text in it, I want remove all the special characters except dot and comma.

For example, this is what have:

[u' %$HI# Jhon, $how$ are *&$%you.%$

I'm trying to produce the following string:

HI Jhon, how are you.

I tried this

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replaceAll("[^a-zA-Z]+","");

But it removes commas and dots also. I want commas and dots to be there.

Finally i found solution:

Python:

import re

my_str = "[u' %$HI# Jhon, $how$ are *&$%you.%$"
my_new_string = re.sub('[^.,a-zA-Z0-9 \n\.]', '', my_str)
print (my_new_string)

Java:

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replaceAll("[^ .,a-zA-Z0-9]");

Thanks all. I Don't know whats wrong with my question, Don't have freedom to ask. :-(

like image 475
Sai Avatar asked Sep 06 '25 03:09

Sai


1 Answers

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replace(/[^.,a-zA-Z]/g, '');

You need to add comma and dot with all characters inside the brackets, like I just did.

And you might want to include numbers too.

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replace(/[^.,a-zA-Z0-9]/g, '');

Edited

And, as noted below, your output also needs spaces:

("[u' %$HI# Jhon, $how$ are *&$%you.%$").replace(/[^.,a-zA-Z ]/g, '');
like image 158
Keith Avatar answered Sep 07 '25 17:09

Keith