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 char
I think you are looking for a code like this to solve your problem without any looping
:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StripChars {
public static void main(String[] args) {
// prints: Just to clarify I will have strings of varying lengths
System.out.println(
replace("Just to clarify, I will have strings of varying lengths.",
",."));
// prints: Solution to my problem on Stackoverflow will cost me 0
System.out.println(
replace("Solution to my problem on stackoverflow will cost me $0.",
".$"));
}
static String replace(String line, String charsToBeReplaced) {
Pattern p = Pattern.compile("(.{1})");
Matcher m = p.matcher(charsToBeReplaced);
return line.replaceAll(m.replaceAll("\\\\$1\\|"), "");
}
}
To take care of special regex characters (meta-characters) in input replace method is first putting \ (backslash) before each character and a | (pipe) after each character in your input. So an input of ",."
will become "\\,|\\.|"
Once that is done then replacement is pretty simple: for every matching char replace it by a blank.
Not used in this solution but here is the pattern to detect presence of ANY special regex character in Java:
Pattern metachars = Pattern.compile(
"^.*?(\\(|\\[|\\{|\\^|\\-|\\$|\\||\\]|\\}|\\)|\\?|\\*|\\+|\\.).*?$");