首页 > 解决方案 > 正则表达式麻烦,结合负和正匹配

问题描述

在为我的问题创建完美的正则表达式时,我遇到了很多问题。希望这里有人可以帮助我。我正在尝试查找 SQL 查询中的所有变量。

举个例子:

select *, 'string with :port in the text'
from table
where a = :variable
// and this is commented out :oldvariable

我们曾经使用r':(\w+)', 来查找变量,以查找后面的所有单词:。但是,我想过滤掉后面的线条//和里面的任何""东西''

正则表达式的首选输出应该是:variable.

:port&:oldvariable不应该在那里。

我可以每行执行正则表达式,这样可能有助于解决方案。

标签: javascriptregex

解决方案


这是 php 中的一个示例

<?php

$testo_pagina = "select *, 'string with :port in the text'
from table
where a = :variable
// and this is commented out :oldvariable";

if(preg_match_all('~^([\w\s\*,=]+)(:.+?)\b~im', $testo_pagina, $matches, PREG_SET_ORDER))
{
    foreach ($matches as $key => $value)
    {
        print_r($value);
    }
}

输出是:

Array
(
    [0] => from table
where a = :variable
    [1] => from table
where a = 
    [2] => :variable
)

这里的想法是在正则表达式的第一部分“ ([\w\s*,=]+) ”中只允许接受的字符,因此不允许/"'字符。希望这会有所帮助。


推荐阅读