Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing certain characters from a string

Tags:

I am thinking about using String.replaceAll() to remove certain characters in my string. It is unclear which characters are going to be removed (i.e. which characters I want to remove), but I would assume that any character is valid (like [a-zA-Z] and things like $%!, etc).

I came across http://www.java-tips.org/java-se-tips/java.lang/strip-certain-characters-from-a-string.html but surely there is a better way than iterating over each character...

Any thoughts on this?

Thanks

EXAMPLE:

Just to clarify, I will have strings of varying lengths. I want to strip characters from it, the exact ones to be determined at runtime, and return the resulting string.

Taking the paragraph above and allowing me to strip out the ",.", I would return the string:

Just to clarify I will have strings of varying lengths I want to strip characters from it the exact ones to be determined at runtime and return the resulting string

As an aside, I know that replaceAll() uses regular expressions, so if I wanted to strip out the characters "$,.", I would need to escape them too, right?

like image 304
ekawas Avatar asked Mar 21 '11 03:03

ekawas


People also ask

How do I remove a specific character from a string?

You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.

How do I remove certain letters from a string in Python?

You can remove a character from a Python string using replace() or translate(). Both these methods replace a character or string with a given value. If an empty string is specified, the character or string you select is removed from the string without a replacement.


1 Answers

You might want to start by specifying which character you WANT to keep, try something like:

"mystring".replaceAll("[^a-zA-Z]", "")​ 

To only keep letters.

like image 177
Abdullah Jibaly Avatar answered Sep 28 '22 11:09

Abdullah Jibaly