[英]want a regular expression which will validate java variables with only one comma in between
I have a regex which I use to validate a string. 我有一个正则表达式,用于验证字符串。
String s = SELECT column1,column2 GROUPBY column3 AS AliasName
regex = ^SELECT\s+[[a-zA-Z_$][a-zA-Z_$0-9]*,*]+[a-zA-Z_$][a-zA-Z_$0-9]?\s+GROUPBY\s+[[a-zA-Z_$][a-zA-Z_$0-9]*,*]+[a-zA-Z_$][a-zA-Z_$0-9]?\s+AS\s+[a-zA-Z_$][a-zA-Z_$0-9]*$
This validation works but I need help with changing the regex so it only allows one comma in between each Java variable and doesn't allow it before the first column. 该验证有效,但是我需要更改正则表达式的帮助,因此它仅允许在每个Java变量之间使用逗号,并且不允许在第一列之前使用逗号。
For example, the following String should not match but it does: 例如,以下字符串不匹配,但可以匹配:
String s2 = SELECT ,column1,,column2 GROUPBY column3 AS AliasName
Also, I would like to change it so the SELECT
, GROUPBY
, and AS
could be uppercase or lower case. 另外,我想更改它,以便
SELECT
, GROUPBY
和AS
可以大写或小写。 I know I could use an alternation |
我知道我可以交替使用
|
but I would prefer a different way. 但我希望采用其他方式。
Try it like this: 像这样尝试:
(?i)^SELECT ([a-zA-Z_$][a-zA-Z_$0-9]+,)*([a-zA-Z_$][a-zA-Z_$0-9]+) (?:(GROUPBY) ([a-zA-Z_$][a-zA-Z_$0-9]+,)*([a-zA-Z_$][a-zA-Z_$0-9]+))?(?: AS ([a-zA-Z_$][a-zA-Z_$0-9]+))?
Online Demo 在线演示
Code Sample 代码样例
The easiest way to allow lowercase too is to switch the regex to case-insensitive using the inline modifier (?i)
. 允许小写字母的最简单方法是使用内联修饰符
(?i)
将正则表达式切换为不区分大小写。
PS: Your query looks incomplete. PS:您的查询看起来不完整。 There is no
FROM
part? 没有
FROM
部分? PPS: You may want to look into different solutions since regular expressions cannot fully match and validate SQL syntax. PPS:您可能要研究不同的解决方案,因为正则表达式不能完全匹配和验证SQL语法。 You can try to tokenize the query .
您可以尝试标记查询 。 Or, even better, use a parser instead.
或者,甚至更好的是,使用解析器。 ANTLR has some SQL grammar .
ANTLR有一些SQL语法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.