目的是这样的:
一配置文件,预设一些指令的类型及需要相应执行的操作,例如
ADD%#新增记录,EDIT??#修改记录,DELETE??#删除记录... (%表示任意字符,?表示一个字符)
当用户输入一串指令后,判断它输入的内容及类型,指行相应的操作。
例如 ADD5566,则它的类型是"新增操作",新增的内容是5566
     EDIT23,则它的类型是"修改记录",修改的内容是23
     DELETE78,则它的类型是"删除记录",修改的内容是78请教如何用正则表达式将指令串去逐个和配置文件中的预定指令去匹配,然后得出它的"类型"和它的值.请大侠们给个思路吧.百分感谢

解决方案 »

  1.   

    Matcher match1 = Pattern.compile("ADD(.*)").matcher(yourStr);
            Matcher match2 = Pattern.compile("EDIT(.{2})").matcher(yourStr);
            Matcher match3 = Pattern.compile("DELETE(.{2})").matcher(yourStr);
            
            if (match1.find())
            {
                valueStr = match1.group(1);
                addMethod(valueStr);
            }
            
            if (match2.find())
            {
                valueStr = match2.group(1);
                editMethod(valueStr);
            }
            
            if (match2.find())
            {
                valueStr = match3.group(1);
                deleteMethod(valueStr);
            }
      

  2.   

    private static ArrayList parseCommand(String command) {
         String[] myCommands = {"ADD", "EDIT", "DELETE"};
         ArrayList commands = new ArrayList();
      Pattern p=Pattern.compile(myCommands[0] + "(.*)|" +
      myCommands[1] + "(.*)|" + myCommands[2] + "(.*)");
     
      String[] commamdList = command.split(",");
      for(int j = 0; j < commamdList.length; j++){
      commamdList[j] = commamdList[j].trim();
        Matcher m=p.matcher(commamdList[j]);
        while(m.find()){
        for(int i = 0; i < m.groupCount(); i++){
        String unit = m.group(i + 1);
        System.out.println("unit:" + unit + " " + m.groupCount());
        if(unit == null){
        continue;
        }
        commands.add(myCommands[i] + ": " + unit);
        }
        }
      }
    return commands;
    }  public static void main(String[] args){
      System.out.println(parseCommand("ADD3423, EDIT8787 , DELETE556"));
             }output:[ADD: 3423, EDIT: 8787, DELETE: 556]
      

  3.   

    楼上几位的似乎都不完善吧,按楼主的意思,像ADD之类的必然是串的开头,最好加个“^”吧
      

  4.   

    如果只输入"ADD",能否得出类型是ADD,值为空?