-5

I am using String#replace() to convert an RGB string into an RGBa one. This is the current code:

inputString = "rgb(255, 182, 121)";
outputString = inputString.replace( "rgb", "rgba" ).replace( ")", ",255)" ).replace( " ", "" );

In the example above, the output will be "rgba(255,182,121,255)". This solution, however, looks a bit convoluted, and I think it could be done more elegantly using a regular expression.

How can I write a regular expression (in Java) to accomplish the same thing as the code above?

Drenmi
  • 8,492
  • 4
  • 42
  • 51
Avinash Jadhav
  • 1,243
  • 2
  • 12
  • 20

1 Answers1

2

Sure you can:

    inputString.replaceFirst("rgb\\((\\d++),\\s*(\\d++),\\s*(\\d++)\\)", "rgba($1,$2,$3,255)");

If you use it more often, better pre-compile the regex with Pattern.compile().

Vampire
  • 35,631
  • 4
  • 76
  • 102