Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing multiple char from a string in java

Tags:

java

string

I have a PHP script <?=str_replace(array('(',')','-',' ','.'), "", $rs["hq_tel"])?> this is a string replace function that take array of chars and replace them if find any of the char in string. Is there any java equivalent of the function. I found some ways but some are using loop and some repeating the statements but not found any single line solution like this in java.

Thanks in advance.

like image 715
NoNaMe Avatar asked Jun 19 '13 10:06

NoNaMe


People also ask

How do you replace all occurrences of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

How do I replace a character in a string in Java?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

How do I replace two characters in a string?

To replace multiple characters in a string: Store the characters to be replaced and the replacements in a list. Use a for loop to iterate over the list. Use the str. replace() method to replace each character in the string.


2 Answers

your solution is here..

Replace all special character

str.replaceAll("[^\\dA-Za-z ]", "");

Replace specific special character

str.replaceAll("[()?:!.,;{}]+", " ");
like image 158
Ganesh Rengarajan Avatar answered Oct 01 '22 03:10

Ganesh Rengarajan


You can use a regex like this:

//char1, char2 will be replaced by the replacement String. You can add more characters if you want!
String.replaceAll("[char1char2]", "replacement");

where the first parameter is the regex and the second parameter is the replacement.

Refer the docs on how to escape special characters(in case you need to!).

like image 33
Rahul Avatar answered Oct 01 '22 01:10

Rahul