-3

In my android app, I have this format xxxx xxxx xxxx xxxx for credit card number but when I insert AMEX with 15 digits I want it to be shown as xxxx xxxx xxxx 1234 Instead, I get xxxx xxxx xxx1 234. How do I fix this?

I'm using this code:

textCardNumber.setText("Card Number: " + mActivity.maskedAccountNumber.replaceAll("(.{4})(?!$)", "$1 "));
tynn
  • 38,113
  • 8
  • 108
  • 143
Katherina
  • 379
  • 1
  • 2
  • 15

2 Answers2

0

You're using a simple replace function which expects numbers of length a multiple of 4. You could just improve your formatting algorithm of course. But the most simple solution would be to assure the length of the input string.

In your specific case you could just left pad the input with an x for AMEX

String maskedAccountNumber = mActivity.maskedAccountNumber;
if (maskedAccountNumber.length() == 15)
    maskedAccountNumber = "x" + maskedAccountNumber;
textCardNumber.setText("Card Number: " + maskedAccountNumber.replaceAll("(.{4})(?!$)", "$1 "));
tynn
  • 38,113
  • 8
  • 108
  • 143
0

The simplest way would be to just use -

String acc = mActivity.maskedAccountNumber;
textCardNumber.setText("Card Number: xxxx xxxx xxxx " + acc.substring(acc.length() - 4));
prempal
  • 71
  • 5