Advertisement
SotirovG

FancyBarcodes

Apr 2nd, 2021
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. package JavaFundamentals.FinalExamExamples;
  2.  
  3. import java.util.Scanner;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. public class FancyBarcodes_02 {
  8.     public static void main(String[] args) {
  9.         Scanner read = new Scanner(System.in);
  10.         // regex --> "@#+(?<barcode>[a-zA-Z0-9A-Z]{6,})@#+"
  11.  
  12.         int loop = Integer.parseInt(read.nextLine());
  13.  
  14.         for (int index = 0; index < loop; index++) {
  15.             // inside the loop we read barcode and compile the regex
  16.             String barcode = read.nextLine();
  17.             Matcher matcher = Pattern.compile("@#+(?<barcode>[a-zA-Z0-9A-Z]{6,})@#+").matcher(barcode);
  18.           if (matcher.find()){
  19.               matcher = Pattern.compile("\\d").matcher(barcode); // --> taking the digit from the regex
  20.               StringBuilder group = new StringBuilder();
  21.               while(matcher.find()){
  22.                   group.append(matcher.group());
  23.               }
  24.               if (group.toString().length() == 0){
  25.                   group = new StringBuilder("00");
  26.               }
  27.               System.out.printf("Product group: %s%n",group.toString());
  28.           }else{
  29.               System.out.println("Invalid barcode");
  30.           }
  31.         }
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.     }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement