javaregexmaskingcucm

Using regex to define masks for numbers in Java


I am trying to define a set of rules, that will compute a mask based on the number it is given. For example I am trying to return a mask of 8472952424 of any number that start with 12, 13, 14, Or return 847235XXXX for any number that starts with 7 or 8.

The input numbers are 4 digit Integers and the return is a String. Do I need to convert the integers to string before I do the regex on them, and I am also not sure how to construct the expressions.

Edit I have too much criteria to be done using separate if statements for each case. I am matching extension numbers to masks so it could be inserted correctly on Cisco CallManager database (in case you are curious)

Edit

This is what I have done for one of the cases but this is still not matching correctly:

public String lookupMask(int ext){
   //convert to String
   StringBuilder sb = new StringBuilder();
   sb.append(ext);
   String extString = sb.toString();

   //compile and match pattern
   Pattern p = Pattern.compile("^[12|13|14|15|17|19|42]");
   Matcher m = p.matcher(extString);
   if(m.matches()){
       return "8472952424";
   }
   return null;
}

Solution

  • An example with Pattern could be this:

    package test;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Pattern;
    
    public class Main {
        // working Pattern
        private static final Pattern PATTERN = Pattern.compile("^((1[234579])|42)");
        // Your Pattern won't work because although it takes in account the start of the 
        // input, the OR within a character class does not exempt you to write round brackets 
        // around sequential characters such as "12". 
        // In fact here, the OR will be interpreted as the "|" character in the class, thus 
        // allowing it as a start character.
        private static final Pattern NON_WORKING_PATTERN = Pattern.compile("^[12|13|14|15|17|19|42]");
        private static final String STARTS_WITH_1_234 = "8472952424";
        private static final String STARTS_WITH_ANYTHING_ELSE = "847295XXXX";
    
        public static void main(String[] args) {
            // NON_WORKING_PATTERN "works" on "33333"
            System.out.println(NON_WORKING_PATTERN.matcher("33333").find());
            int[] testIntegers = new int[]{1200, 1300, 1400, 1500, 1700, 1900, 4200, 0000};
            List<String> results = new ArrayList<String>();
            for (int test: testIntegers) {
                if (PATTERN.matcher(String.valueOf(test)).find()) {
                    results.add(STARTS_WITH_1_234);
                }
                else {
                    results.add(STARTS_WITH_ANYTHING_ELSE);
                }
            }
            System.out.println(results);
        }
    }
    

    Output:

    true
    [8472952424, 8472952424, 8472952424, 8472952424, 8472952424, 8472952424, 8472952424, 847295XXXX]