Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
Java equivalent of this JavaScript regex code?

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!