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

186
Vistas
Replace last instance of comma with 'and' in a string

I have a string of comma separated words e.g. "a, b, c".
I need to replace the last comma instance with “and”, to make it look like "a, b and c".

I've tried using replaceFirst like this:

"a, b, c".replaceFirst("(,)[^,]+$", " and")

But it doesn't work. It replaces everything after the last comma with “and” rather than just the comma producing "a, b and".

How to make it work?
I'm on java8.

Ps. I thought that it's obvious, but it seems like I need to clarify, that I'm looking for a generic solution that works with any number of comma separated tokens, i.e. 'a, b, ...., c'

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

I don't think you need anything particular from Java 8 here. If you want to go the regex route with String#replaceAll(), then you can consider using the following pattern:

(.*), (.*)

Simple rebuild the string using the first and second capture groups, with and in between them. The first pattern (.*) will greedily consume everything until the last comma, exactly the behavior you want. Then, the second (.*) does cleanup to capture the final letter/string.

String input = "a, b, c";
input = input.replaceAll("(.*), (.*)", "$1 and $2");
System.out.println(input);

Output:

a, b and c
over 4 years ago · Santiago Trujillo Denunciar

0

I think the replaceFirst is better than replaceAll for you because you want to replace only once not all, and it run faster than replaceAll.

  1. using ${number} to capturing groups.

    "a, b, c".replaceFirst(",([^,]+)$", " and$1"); // return "a, b and c"
    
  2. using positive lookahead:

    "a, b, c".replaceFirst(",(?=[^,]+$)", " and"); // return "a, b and c"
    
over 4 years ago · Santiago Trujillo Denunciar

0

You can also achieve same thing using lastIndexOf :

String str = "a, b, c";
StringBuilder builder = new StringBuilder(str);
int lastindex = str.lastIndexOf(",");
builder.replace(lastindex, lastindex + 1, " and" );
System.out.println(builder.toString());

Output:

a, b and c
over 4 years ago · Santiago Trujillo 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