对于常用的SQL语句,有时为了规整,必须让关键字大写,但对有的不规范的,我们可以用正则表达式修改为大写,具体步骤为:
1.定义要大写的关键字
const
sMatch: array[1..34] of string = ('select', 'case', 'begin', 'and', 'from', 'where', 'update', 'delete',
'left', 'join', 'full', 'right', 'inner', 'outer', 'declare', 'set', 'distinct', 'if', 'is', 'null','order',
'group', 'by', 'asc', 'desc', 'or', 'exists', 'having', 'sum', 'count', 'average', 'ave', 'raise', 'error');
2.定义规则
for i := Low(sMatch) to High(sMatch) do
if Rgr.Exec(Memo1.Text) then
repeat
str := Rgr.Match[1];
str1 := StringReplace(str1,str,UpperCase(str),[rfReplaceAll]);
until not Rgr.ExecNext;
Memo2.Text :=str1;
整个代码为:
1
var
2 i: Integer;
3 Rgr: TRegExpr;
4 sExpr,str,str1: string ;
5 begin
6 Memo1.Lines.Clear;
7 Memo1.Lines.Text : = ' select * from delphi WHERE id=1 and kind=3 ' + # 10 # 13
8 + ' ordER By id ' ;
9 Rgr : = TRegExpr.Create;
10 try
11 Rgr.ModifierI : = True;
12 for i : = Low(sMatch) to High(sMatch) do
13 sExpr : = sExpr + sMatch[i] + ' | ' ;
14 sExpr : = ' ( ' + Copy(sExpr, 1 , Length(sExpr) - 1 ) + ' ) ' ;
15 Rgr.Expression : = sExpr;
16 str1 : = Memo1.Text;
17 if Rgr.Exec(Memo1.Text) then
18 repeat
19 str : = Rgr.Match[ 1 ];
20 str1 : = StringReplace(str1,str,UpperCase(str),[rfReplaceAll]);
21 until not Rgr.ExecNext;
22 Memo2.Text : = str1;
23 finally
24 Rgr.Free;
25 end;
26 end;
2 i: Integer;
3 Rgr: TRegExpr;
4 sExpr,str,str1: string ;
5 begin
6 Memo1.Lines.Clear;
7 Memo1.Lines.Text : = ' select * from delphi WHERE id=1 and kind=3 ' + # 10 # 13
8 + ' ordER By id ' ;
9 Rgr : = TRegExpr.Create;
10 try
11 Rgr.ModifierI : = True;
12 for i : = Low(sMatch) to High(sMatch) do
13 sExpr : = sExpr + sMatch[i] + ' | ' ;
14 sExpr : = ' ( ' + Copy(sExpr, 1 , Length(sExpr) - 1 ) + ' ) ' ;
15 Rgr.Expression : = sExpr;
16 str1 : = Memo1.Text;
17 if Rgr.Exec(Memo1.Text) then
18 repeat
19 str : = Rgr.Match[ 1 ];
20 str1 : = StringReplace(str1,str,UpperCase(str),[rfReplaceAll]);
21 until not Rgr.ExecNext;
22 Memo2.Text : = str1;
23 finally
24 Rgr.Free;
25 end;
26 end;