-1

我正在尝试定义一组规则,它将根据给出的数字计算掩码。例如,我试图返回以 12、13、14 开头的任何数字的 8472952424 掩码,或者为以 7 或 8 开头的任何数字返回 847235XXXX。

输入数字是 4 位整数,返回是字符串。在对它们执行正则表达式之前,我是否需要将整数转换为字符串,而且我也不确定如何构造表达式。

编辑 对于每种情况,我有太多的标准要使用单独的 if 语句来完成。我将分机号码与掩码匹配,以便可以将其正确插入 Cisco CallManager 数据库(以防您好奇)

编辑

这是我为其中一种情况所做的,但这仍然没有正确匹配:

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;
}
4

1 回答 1

1

一个例子Pattern可能是这样的:

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);
    }
}

输出:

true
[8472952424, 8472952424, 8472952424, 8472952424, 8472952424, 8472952424, 8472952424, 847295XXXX]
于 2013-06-25T15:48:40.250 回答