提取第二个字符串可能存在或不存在的两个字符串之间的字符串

时间:2016-01-15 08:30:05

标签: java mysql regex string

我想在java中解析一个sql查询。它是我项目的一部分。 现在我需要从'中提取参数。条款。因为它们存在于'之间。和'其中'条款我使用以下模式进行匹配,

     Pattern p = Pattern.compile("from" + "(.*?)" + "(where)?");

由于在查询中可能存在或不存在where子句,因此我使用了'?'在哪里。但我没有得到预期的'来自'我使用像

这样的查询时的参数
     select * from student;

我对正则表达式并不熟悉。请帮忙

1 个答案:

答案 0 :(得分:0)

提示:为什么不只是substring呢?

/*
Regex explanation:
  'from'    - when found `from` char sequence
  '\\s*'    - skip whitespace
  '(.*?)'   - capture some chars in `non-greedy` mode
  '('       - and then
    'where' - must be `where` char sequence
    '|;'    - or a semicolon
    '|$'    - or end of matching string
  ')'  
*/
static Pattern p = Pattern.compile("from\\s*(.*?)(where|;|$)");

static String extract1(String query) {

  String tables = null;

  Matcher m = p.matcher(query);
  if (m.find())
    tables = m.group(1).trim();

  return tables;
}

static String extract2(String query) {
  String term = query.toLowerCase();
  int from = term.indexOf("from");
  if (from < 0)
    return null;

  int to = term.indexOf("where");
  if (to < 0) {
    to = term.length();
    while (term.charAt(to - 1) == ';')
      to--;
  }

  return query.substring(from + 4, to).trim();
}

public static void main(String[] args) {
  String query1 = "select * from table as t";
  String query2 = "select * from table as t;";
  String query3 = "select * from table as u where a = b";
  String query4 = "select * from table as u where a = b;";

  String t1, t2;

  t1 = extract1(query1);
  t2 = extract2(query1);
  System.out.printf("\"%s\":\n  %s\n  %s\n\n", query1, t1, t2);

  t1 = extract1(query2);
  t2 = extract2(query2);
  System.out.printf("\"%s\":\n  %s\n  %s\n\n", query2, t1, t2);

  t1 = extract1(query3);
  t2 = extract2(query3);
  System.out.printf("\"%s\":\n  %s\n  %s\n\n", query3, t1, t2);

  t1 = extract1(query4);
  t2 = extract2(query4);
  System.out.printf("\"%s\":\n  %s\n  %s\n\n", query4, t1, t2);
}

结果:

"select * from table as t":
  table as t
  table as t

"select * from table as t;":
  table as t
  table as t

"select * from table as u where a = b":
  table as u
  table as u

"select * from table as u where a = b;":
  table as u
  table as u