fork download
  1. import java.util.*;
  2. import java.util.regex.*;
  3. import java.io.*;
  4. /* Name of the class has to be "Main" only if the class is public. */
  5. class Ideone
  6. {
  7. public static void main (String[] args) throws java.lang.Exception
  8. {
  9. List<String> strs = Arrays.asList("Фамилия Имя Отчество", "Фамилия Имя", "Фамилия");
  10. Pattern p = Pattern.compile("\\s*(\\S{0,20})\\S*\\s*(\\S)?.*");
  11. for (String str : strs) {
  12. Matcher m = p.matcher(str);
  13. System.out.println(m.replaceAll(x -> x.group(1) + (x.group(2) == null ? "" : " " + x.group(2) + ".")) );
  14. }
  15. }
  16. }
Success #stdin #stdout 0.12s 50860KB
stdin
Standard input is empty
stdout
Фамилия И.
Фамилия И.
Фамилия