Avinash Jadhav Avinash Jadhav - 1 year ago 98
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download