【发布时间】:2014-05-15 07:29:25
【问题描述】:
我需要一个正则表达式,它匹配下面的 java 字符串。
select * from test
select * from test where a=100
select * from test where a=100 and b=100
select 语句可能包含也可能不包含 where 条件,也可能包含 1 到 n 个条件,我需要一个正则表达式来匹配所有这些条件,谁能帮忙
我尝试使用下面的正则表达式匹配字符串,但失败了
select (([A-Za-z0-9]{1,20}(|\\,))*|\\*) from ([A-Za-z0-9]{1,20})( where ([A-Za-z0-9]{1,20}((| )(\\=|\\>|\\<)(| ))[A-Za-z0-9]{1,20})|$)
标准:
i) 字符串应以 select
开头ii) 如果 where 存在,则后面应该有一对变量和值
like below:
`select * from test where a=10;`
iii) 在两个变量和值对之间 and 应该存在
like below:
`select * from test where a=10 and b=10`
iv) 字符串可能包含也可能不包含 where
v) 字符串不应以 and
结尾public class Test {
public static Pattern pattern;
public static Matcher matcher;
private static final String PATTERN="(\\s)*select(\\s)+((\\*)|([a-zA-Z0-9]+))(\\s)+from(\\s)+[a-zA-Z0-9]*(\\s)+where(\\s)+([a-zA-Z0-9]*(\\s)*=(\\s)*[0-9]*)+(\\s)*((\\s)*and(\\s)*([a-zA-Z0-9]*(\\s)*=(\\s)*[0-9]*))*(\\s)*";
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String data;
pattern=Pattern.compile(PATTERN,Pattern.CASE_INSENSITIVE);
do{
data=br.readLine();
matcher=pattern.matcher(data);
if(matcher.find()){
System.out.print("True");
}else{
System.out.print("false");
}
System.out.print(":"+data+":\n");
}while(data!="exit");
}
}
测试用例(应为真)
从测试中选择一个
从 a=10 的测试中选择一个
从 a=10 和 b=10 的测试中选择一个
从 a=10 and b=10 and c=10 的测试中选择 a
测试用例(应显示为 false)
从测试中选择一个
从测试中选择 a=10 并且
从 a=10 b=10 的测试中选择一个
从 a=10 和 b=10 的测试中选择一个并且
谢谢
【问题讨论】:
-
你应该开始做这件事并提交你的进度:这样我们就知道如何衡量答案的细节了。
-
@Pradeep 我会把它放到你的问题中
-
请将您的正则表达式放在实际问题中:它实际上不属于评论;你会像现在这样吸引反对票。
-
所以你只想匹配以
select * from test开头的每一行,或者你想解析条件还是......?你能给出预期的输出吗? -
它类似于 sql select 语句,可能因情况而异。下面是示例字符串 select a from test select a,b from group select * from group where a=1 and b=10 etc