gpt4 book ai didi

java - 提取两个字符串之间的字符串,其中第二个字符串可能存在也可能不存在

转载 作者:行者123 更新时间:2023-11-29 21:37:28 25 4
gpt4 key购买 nike

我想用java解析sql查询。这是我项目的一部分。现在我需要提取“from”子句中的参数。由于它们存在于“from”和“where”子句之间,我使用以下模式进行匹配,

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

由于查询中可能存在也可能不存在 where 子句,所以我使用了“?”之后在哪里。但是当我使用像

这样的查询时,我没有得到预期的“来自”参数
     select * from student;

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

最佳答案

提示:为什么不直接子字符串呢?

/*
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

关于java - 提取两个字符串之间的字符串,其中第二个字符串可能存在也可能不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34806970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com