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.
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.
String are immutable in Java. You can't change them. You need to create a new string with the character replaced.
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.
your solution is here..
Replace all special character
str.replaceAll("[^\\dA-Za-z ]", "");
Replace specific special character
str.replaceAll("[()?:!.,;{}]+", " ");
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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With