Avinash Jadhav Avinash Jadhav - 5 months ago 36
Java Question

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

I am trying to replace the String using

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?


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