Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda