大家好,我想请教大家一个正则表达式应该怎么写。下面是一种OQL(object   query   language), 我现在想验证它是否包含那个id。在括号中的是子语句,他们也有可能包含“id”, 正则表达式需要能区分主语句中的id和子语句中的id,只验证主语句是是否有id。select name, id, country, city, (select id, firstname, lastname from contacts), (select id, name, amount from opportunities) from account where name like '%a%'还有,主语句中的id也有可能在子语句的后面或两/多个子语句中间. 例如:select name, country, city, (select id, firstname, lastname from contacts), (select id, name, amount from opportunities), id from account where name like '%a%'select name, country, city, (select id, firstname, lastname from contacts), id, (select id, name, amount from opportunities) from account where name like '%a%'谢谢大家!

解决方案 »

  1.   

    public class Main {    public static void main(String[] args) {
         String testStr = "select   name,   id,   country,   city,   (select   id,   firstname,   lastname   from   contacts),   (select   id,   name,   amount   from   opportunities)   from   account   where   name   like   '%a%'";
         // remove all sub queries
         testStr = testStr.replaceAll("[(].+?[)]", "");
         if (testStr.matches("(?i).+\\bid\\b.+")) {
         System.out.println("It has a valid 'id'!");
         } else {
         System.out.println("No id was found!");
         }
        }
    }这个能判断是否含有id,但是,遇到 SELECT X AS id FROM XXX 就没有办法了
      

  2.   

    将包含在括号内的整个子语句删除先 再做判断
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class Test {
    public static void main(String[] args) {
    String input1 = "select   name,   id,   country,   city,   (select   id,   firstname,   lastname   from   contacts),   (select   id,   name,   amount   from   opportunities)   from   account   where   name   like   '%a%' ";
    //String input2 = "select   name,   country,   city,   (select   id,   firstname,   lastname   from   contacts),   (select   id,   name,   amount   from   opportunities),   id   from   account   where   name   like   '%a%' ";
            //String input3 = "select   name,   country,   city,   (select   id,   firstname,   lastname   from   contacts),   id,   (select   id,   name,   amount   from   opportunities)   from   account   where   name   like   '%a%' ";
            
    String input = input1.replaceAll("\\(.*?id.*?\\)", "");

    System.out.println(input);

    Pattern p = Pattern.compile("id");
    Matcher m = p.matcher(input);
    while (m.find()) {
    System.out.println(m.group());
    }
    }
    }/*
    select   name,   id,   country,   city,   ,      from   account   where   name   like   '%a%' 
    id
    */