Regex username validator specific to use case

 import java.io.BufferedReader;  
 import java.io.IOException;  
 import java.io.InputStreamReader;  
 import java.nio.charset.StandardCharsets;  
 import java.util.ArrayList;  
 import java.util.List;  
 import java.util.regex.Matcher;  
 import java.util.regex.Pattern;  
 /**  
  * Sample data :  
  * "C:\Program Files\Java\jdk1.8.0_192\bin\java.exe"  
  * Joe$Schmoe002  
  * Bob$Smith  
  * Bob$$Smith  
  * JaneAusten  
  * 001Smith  
  * $Smith  
  * joe$Schmoe002  
  * Joe$Schmoe0023  
  * Joe$ Schmoe002  
  * Joe$schmoe0023  
  * J$SJoe$Schmoe002  
  * Bob$Smith  
  * Bob$$Smith  
  * JaneAusten  
  * 001Smith  
  * $Smith  
  * joe$Schmoe002  
  * Joe$Schmoe0023  
  * Joe$ Schmoe002  
  * Joe$schmoe0023  
  * ^D  
  * J$S  
  * Username : Joe$Schmoe002 is true  
  * Username : Bob$Smith is true  
  * Username : Bob$$Smith is false  
  * Username : JaneAusten is false  
  * Username : 001Smith is false  
  * Username : $Smith is false  
  * Username : joe$Schmoe002 is false  
  * Username : Joe$Schmoe0023 is false  
  * Username : Joe$ Schmoe002 is false  
  * Username : Joe$schmoe0023 is false  
  * Username : J$S is true  
  *  
  * Process finished with exit code 0  
  */  
 public class Main {  
   private static final Pattern pattern = Pattern.compile("([A-Z][a-zA-z]*?)([$])([A-Z][a-zA-z]*?)(\\d{0,3}$)");  
   /**  
    * Iterate through each line of input.  
    */  
   public static void main(String[] args) throws Exception {  
     Main main = new Main();  
     List<String> userNames = main.getUserNamesFromConsole();  
     main.validateUserNames(userNames);  
   }  
   private void validateUserNames(List<String> userNames){  
     userNames.forEach( e -> {  
       Matcher matcher = pattern.matcher(e);  
       System.out.printf("Username : %s is %s %n", e, matcher.find());  
     });  
   }  
   private List<String> getUserNamesFromConsole() throws IOException {  
     List<String> userNames = new ArrayList<>();  
     InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);  
     BufferedReader in = new BufferedReader(reader);  
     String line;  
     while ((line = in.readLine()) != null) {  
       System.out.println(line);  
       userNames.add(line);  
     }  
     return userNames;  
   }  
 }  

Comments

Popular posts from this blog

FileSystemUtils

Report

AbstractTestNgBaseTest