I have this JavaScript code:
highlightTerm = "h=e;?l*l{o";
highlightTerm = highlightTerm.replace(/[\\;]/g, ' ');
highlightTerm = highlightTerm.replace(/([{}<>\/=:])(?=(?:[^"]|"[^"]*")*$)/g, '\\$&');
highlightTerm = highlightTerm.replace(/"/g, '\"');
highlightTerm = highlightTerm.trim();
console.log(highlightTerm); // "h\=e ?l*l\{o"
I am trying to find the Java equivalent. I've tried the following bit it gives a different result:
String highlightTerm = "h=e;?l*l{o";
highlightTerm = highlightTerm.replaceAll("[\\;]", " ");
highlightTerm = highlightTerm.replaceAll("([{}<>\\/=:])(?=(?:[^\"]|\"[^\"]*\")*$)", "\\$&");
highlightTerm = highlightTerm.replaceAll("[\"]", "\\\"");
highlightTerm = highlightTerm.trim();
System.out.println(highlightTerm); // "h=e ?l*l{o"
Any help is much appreciated!
CodePudding user response:
The problem you are having is that '\\$&'
is Javascript mean whole matched string but doesn't mean the same in Java. I don't think there is a one-line solution in Java to solve this problem, but this code should work:
String highlightTerm = "h=e;?l*l{o";
highlightTerm = highlightTerm.replaceAll("[\\;]", " ");
//highlightTerm = highlightTerm.replace(/([{}<>\/=:])(?=(?:[^"]|"[^"]*")*$)/g, '\\$&');
//These lines are replacement for the above line
Pattern pattern = Pattern.compile("([{}<>\\/=:])(?=(?:[^\"]|\"[^\"]*\")*$)");
Matcher matcher = pattern.matcher(highlightTerm);
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
String replacement = "\\" matcher.group(1);
builder.append(highlightTerm, i, matcher.start());
builder.append(replacement);
i = matcher.end();
}
builder.append(highlightTerm.substring(i));
highlightTerm = builder.toString();
//rest of your code
highlightTerm = highlightTerm.replaceAll("[\"]", "\\\"");
highlightTerm = highlightTerm.trim();
System.out.println(highlightTerm);