I have a set of regex replacements that are needed to be applied to a set of String,
For example:
(\"\\s{
You have these 2 replaceAll
calls:
s = s.replaceAll("\\s{2,}"," ");
s = s.replaceAll("\\.([a-zA-Z])",". $1");
You can combine them into a single replaceAll
like this:
s = s.replaceAll("\\s{2,}|(\\.)(?=[a-zA-Z])", "$1 ");
RegEx Demo
Look at Replace multiple substrings at Once and modify it.
Use a Map<Integer, Function<Matcher, String>>
.
Modify the loop to check which group was matched. Then use that group number for getting the replacement lambda.
Pseudo code
Map<Integer, Function<Matcher, String>> replacements = new HashMap<>() {{
put(1, matcher -> "");
put(2, matcher -> " " + matcher.group(2));
}};
String input = "lorem substr1 ipsum substr2 dolor substr3 amet";
// create the pattern joining the keys with '|'. Need to add groups for referencing later
String regexp = "(\\s{2,})|(\\.(?:[a-zA-Z]))";
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(input);
while (m.find()) {
//TODO change to find which groupNum matched
m.appendReplacement(sb, replacements.get(m.group(groupNum)));
}
m.appendTail(sb);
System.out.println(sb.toString()); // lorem repl1 ipsum repl2 dolor repl3 amet