Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing characters from string efficiently

Tags:

java

string

This may sound like a very simple question but how do you remove multiple different characters from a string without having to write a line for each, which is what I have laboriously done. I have written a string example below:

            String word = "Hello, t-his is; an- (example) line."

            word = word.replace(",", "");
            word = word.replace(".", "");
            word = word.replace(";", "");
            word = word.replace("-", "");
            word = word.replace("(", "");
            word = word.replace(")", "");
            System.out.println(word);

Which would produce "Hello this is an example line". A more efficient way is?

like image 392
Harry Jones Avatar asked Sep 18 '26 00:09

Harry Jones


2 Answers

Use

word = word.replaceAll("[,.;\\-()]", "");

Note that special character - (hyphen) should be escaped by double backslashes, because otherwise it is considered to construct a range.

like image 136
Nikita Astrakhantsev Avatar answered Sep 20 '26 14:09

Nikita Astrakhantsev


Although no more efficient than the original replace technique you could use

word = word.replaceAll("\\p{Punct}+", "");

to use a simple expression using replaceAll with a wider range of characters replaced

like image 43
Reimeus Avatar answered Sep 20 '26 13:09

Reimeus