简体   繁体   中英

java format strings based on a pattern

I have a requirement like this. My code generates random strings and it can be alpha, numeric and alphanumeric ones.

Lets say one of the numeric strings are "7882347812". I want to format this to 788.234.7812 based on a pattern like 3chars.3chars.4chars

If its an alphanumeric one like "h34jh8we7k". Then format this to h3/4jh8/we7k based on a pattern like 2chars/4chars/4chars.

If its an alpha one like "jkythjyv". Then format this to jky$thj$yv based on a pattern like 3chars$3chars$2chars.

In general, the generated strings can contain chars [a-zA-Z0-9]. This should be formatted as I mentioned above with any of the special characters. The input should be the string & the formatter and output should be the formatted string. Even a custom formatter is also fine.

I know how to write code for this. Is there any standard way of doing this in Java?

You could do this through replaceAll function.

System.out.println("7882347812".replaceAll("^(\\d{3})(\\d{3})(\\d{4})$", "$1.$2.$3"));

Output:

788.234.7812

OR

System.out.println("foo bar 7882347812".replaceAll("\\b(\\d{3})(\\d{3})(\\d{4})\\b", "$1.$2.$3"));

Output:

foo bar 788.234.7812

I got a solution for this:

MaskFormatter formatter = new MaskFormatter("A-AAAA-AAAA-A");
formatter.setValueContainsLiteralCharacters(false);
System.out.println(formatter.valueToString("1222233334"));

The output would be 1-2222-3333-4

Check http://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html for more details

^(.{3})(.{3})(.{4})$

Try this.This will work.See demo.

http://regex101.com/r/xP1dE9/1

To answer your question:

No

There is no "standard" way in Java to parse strings into a 3chars.3chars.4chars pattern.

As you stated, you already know how to solve this problem, so I guess you don't need everyone's answers?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM