Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

java-8

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'

like image 809
spoonboy Avatar asked Apr 06 '17 06:04

spoonboy


1 Answers

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"
    
like image 167
holi-java Avatar answered Oct 21 '22 20:10

holi-java