Home > front end >  Replace special and optional characters in a string using regex
Replace special and optional characters in a string using regex

Time:07-13

I'm learning regex and trying to work on a small task.

I am taking an input amount as string and converting it into dollar format.

The input string looks like this

123456.78

And the output string looks like this

$123,456.78

Using regex, I have tried to avoid leading zeros and commas that may be present in input amount using below regex. For example if input is like

000,000123456.78
String amount = amount.replaceFirst("^[0,] (?!$)", "");

And I'm producing the output dollar format with

NumberFormat.getCurrencyInstance(new Locale("en", "US")).format(Float.parseFloat(amount));

I'm not able to replace any other characters that may be present apart from the leading zeros. For example, if '$' is already present in the input I am facing an error with the conversion. I'm not sure how to handle this.

CodePudding user response:

Given the following string.

String str = "000,000,000ab$k0b#wef$12322920292029202920456.78";
  • first, get rid of the undesired leading characters including any $.
  • then using a repeating regex, generate the proper commas. This could also be done by modifying the ',' with the locale symbol for numbers.
  • then prepend a $ to the result.
str = str.replaceAll("^([0$\\D] )","");
System.out.println(str);
String result = "";
while (!str.equals(result)) {
     result = str;
     str = str.replaceAll("(\\d)(\\d\\d\\d)(?!\\d)", "$1,$2");
}
System.out.println("$"   result);

prints

12322920292029202920456.78
$12,322,920,292,029,202,920,456.78

  • Related