我希望使用相同的处理程序 (JAVA-Android) 格式化 AMEX 和 ViSA 卡
对于 Visa,我希望看起来像“1234 1234 1234 1234”
我正在使用:
String initial = s.toString();
// remove all non-digits characters
String processed = initial.replaceAll("\\D", "");
// insert a space after all groups of 4 digits that are followed by another digit
processed = processed.replaceFirst("(\\d{4})(?=\\d)", "$1 ");
// to avoid stackoverflow errors, check that the processed is different from what's already
// there before setting
if (!initial.equals(processed)) {
// set the value
s.replace(0, initial.length(), processed);
}
我的问题是:
鉴于我有一个需要用“”替换的位置数组(例如[4,9,14]),我如何使用正则表达式或任何其他方法对其进行格式化以允许删除、粘贴等操作。
最佳答案
您可以简单地使用 for
循环插入 4 位数字间隔的字符。
平衡间隔,保留gap
变量并在每次迭代期间增加它以保持空间的平衡位置,考虑到之前添加的空间,因此使用
String initial = s.toString();
// remove all non-digits characters
String processed = initial.replaceAll("\\D", "");
StringBuilder sb = new StringBuilder(processed);
System.out.println(sb);
int gap = 0;
for (int i = 4; i< sb.length()-1;i+=4){
sb.insert(i + gap,' ');
gap++;
}
要处理这两种情况,您 can use this demo
关于java - 正则表达式在给定位置添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50659360/