Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda