我有这样的要求。我的代码生成随机字符串,它可以是alpha字符串、数字字符串和字母数字字符串。
让我们假设其中一个数字字符串是"7882347812“。我想根据像3 chars.3 chars.4 based这样的模式将它格式化为788.234.7812。
如果是像"h34jh8we7k“这样的字母数字的话。然后根据像2 2chars/4 2chars/4 2chars这样的模式将其格式化为h3/4jh8/we7k。
如果是像"jkythjyv“这样的阿尔法。然后根据像3 2chars$3 2chars$2 2chars这样的模式将其格式化为jky$thj$yv。
通常,生成的字符串可以包含chars a-zA-Z0-9。这应该像我上面提到的那样用任何特殊字符格式化。输入应该是字符串&格式化程序和输出应该是格式化字符串。即使是自定义格式化程序也是可以的。
我知道如何编写代码。在Java中有什么标准的方法来做到这一点吗?
发布于 2014-10-01 20:25:14
我有办法解决这个问题:
MaskFormatter formatter = new MaskFormatter("A-AAAA-AAAA-A");
formatter.setValueContainsLiteralCharacters(false);
System.out.println(formatter.valueToString("1222233334"));产量为1-2222-3333-4。
查看http://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html以获得更多详细信息
发布于 2014-10-01 16:50:34
您可以通过replaceAll函数来完成这一任务。
System.out.println("7882347812".replaceAll("^(\\d{3})(\\d{3})(\\d{4})$", "$1.$2.$3"));输出:
788.234.7812或
System.out.println("foo bar 7882347812".replaceAll("\\b(\\d{3})(\\d{3})(\\d{4})\\b", "$1.$2.$3"));输出:
foo bar 788.234.7812发布于 2014-10-01 16:54:10
^(.{3})(.{3})(.{4})$尝试this.This will work.See演示。
http://regex101.com/r/xP1dE9/1
https://stackoverflow.com/questions/26146391
复制相似问题