Avinash Jadhav Avinash Jadhav - 4 days ago 6
Java Question

How can I use regular expression instead replace method from string?

I am trying to replace the String using

String#replace()
to get the
outputString = "rgba(255,182,121,255)"
.

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


but it doesn't seems the right solution. Can I use regular expressions instead?

Answer

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().

Comments