Nun*_*ong 6 regex sql vbscript
我正在尝试使用正则表达式从SQL语句中删除注释.
这个正则表达式几乎可以工作:
(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|'(?:[^']|'')*'|(--.*)
Run Code Online (Sandbox Code Playgroud)
除了最后一部分不能很好地处理" - "评论.问题是处理SQL字符串,用''分隔.
例如,如果我有
SELECT ' -- Hello -- ' FROM DUAL
Run Code Online (Sandbox Code Playgroud)
它不应该匹配,但它匹配.
这是在ASP/VBscript中.
我想过从右到左匹配,但我不认为VBScript的正则表达式引擎支持它.也试图摆弄负面的背后,但结果并不好.
在PHP中,我正在使用以下代码取消注释SQL:
$sqlComments = '@(([\'"]).*?[^\\\]\2)|((?:\#|--).*?$|/\*(?:[^/*]|/(?!\*)|\*(?!/)|(?R))*\*\/)\s*|(?<=;)\s+@ms';
/* Commented version
$sqlComments = '@
(([\'"]).*?[^\\\]\2) # $1 : Skip single & double quoted expressions
|( # $3 : Match comments
(?:\#|--).*?$ # - Single line comments
| # - Multi line (nested) comments
/\* # . comment open marker
(?: [^/*] # . non comment-marker characters
|/(?!\*) # . ! not a comment open
|\*(?!/) # . ! not a comment close
|(?R) # . recursive case
)* # . repeat eventually
\*\/ # . comment close marker
)\s* # Trim after comments
|(?<=;)\s+ # Trim after semi-colon
@msx';
*/
$uncommentedSQL = trim( preg_replace( $sqlComments, '$1', $sql ) );
preg_match_all( $sqlComments, $sql, $comments );
$extractedComments = array_filter( $comments[ 3 ] );
var_dump( $uncommentedSQL, $extractedComments );
Run Code Online (Sandbox Code Playgroud)
正如您所说,您的正则表达式的其余部分很好,我专注于最后一部分。您需要做的就是验证 是否--位于开头,然后确保它删除所有破折号(如果超过 2 个)。结束正则表达式如下
(^[--]+)
Run Code Online (Sandbox Code Playgroud)
以上仅适用于您想要删除注释破折号而不是整行的情况。如果您确实希望将其后的所有内容都放在行尾,也可以运行以下命令
(^--.*)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6174 次 |
| 最近记录: |