正则表达式匹配常见的 SQL 语法? [英] Regular expression to match common SQL syntax?

查看:52
本文介绍了正则表达式匹配常见的 SQL 语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上周我正在为一段生成一些 SQL 语句的代码编写一些单元测试.

I was writing some Unit tests last week for a piece of code that generated some SQL statements.

我试图找出一个正则表达式来匹配 SELECTINSERTUPDATE 语法,以便我可以验证我的方法是否生成有效SQL,经过 3-4 个小时的搜索和各种正则表达式编辑器的折腾,我放弃了.

I was trying to figure out a regex to match SELECT, INSERT and UPDATE syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up.

我设法获得了部分匹配,但由于引号中的部分可以包含任何字符,因此它会快速扩展以匹配整个语句.

I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement.

任何帮助将不胜感激,我不太擅长正则表达式,但我想了解更多关于它们的信息.

Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them.

顺便说一下,我追求的是 C# RegEx.

By the way it's C# RegEx that I'm after.

澄清

我不想访问数据库,因为这是单元测试的一部分,我不想维护数据库来测试我的代码.这可能比项目寿命更长.

I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project.

推荐答案

正则表达式只能匹配有限状态自动机可以解析的语言,这是非常有限的,而 SQL 是一种语法.可以证明您无法使用正则表达式验证 SQL.因此,您可以停止尝试.

Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. It can be demonstrated you can't validate SQL with a regex. So, you can stop trying.

这篇关于正则表达式匹配常见的 SQL 语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆