簡體   English   中英

正則表達式不放在括號之間

[英]Regex for word not between parentheses

給定一個字符串,匹配單詞首次出現后出現的所有內容。 該單詞不能出現在一對括號內的任何地方,但可以出現其他單詞。 例如:

SELECT
t1.col1,
(SELECT t2.col1 FROM table2 t2
    WHERE t2.id IN(SELECT * FROM table5 WHERE id = t2.id)
) AS alias1,
t1.col2
----------
FROM
table1 t1,
(SELECT id FROM table3 t3 WHERE t3.id = t1.table3_id) t3,
table4 t4

我正在尋找虛線后的所有內容-具體來說,是在單詞FROM的第一個出現之后的所有內容,該內容在一對括號內的任何位置都不會出現

如果Regex不這樣做,我將制作一個PHP語句進行解析。 我也很難過,tough! 我想這樣做,我將不得不通過單詞和括號將字符串標記化?

我認為正則表達式可能不是最好的解決方案,因為當涉及嵌套的paren時,它們可能會非常困難(或不可能)。

我還認為循環遍歷每個字符不是最佳方法,因為這將導致很多不必要的循環。

我認為這是最好的方法:

查找給定字符串的每個出現次數,並計算該出現之前的paren數量。 如果開頭的數目等於結尾的數目,則您具有正確的匹配項。 這樣可以減少循環,您只需要檢查真正要檢查的內容即可。

我做了一個函數findWord ,采用了這種方法。 它與您的示例一起使用,其中$in是您的SQL語句,而$search'FROM'

function findWord( $in, $search ) {

    if( strpos($in, $search) === 0 ) return $in;

    $before = '';
    while( strpos($in, $search, 1) ) {
        $i = strpos($in, $search, 1);
        $before .= substr($in, 0, $i);
        $in = substr($in, $i);

        $count = count_chars($before);

        if( $count[40] == $count[41] )
            return $in;
    }

    return false;
}

除非有人有更好的答案,否則我將采用程序化方法。

/**
 * Find the portion of the SQL statement occurring after
 * the first occurrence of the word 'FROM' (which itself
 * does not appear within parens)
 */
public static function sql_after_from($sql) {
    $arr = str_split($sql);
    $indent = 0;
    $out = '';
    $start = 0;
    $len = count($arr);
    for($x=0; $x < $len; $x++) {
        $c = $arr[$x]; //current character
        if($c == '(') $indent++;
        if($c == ')') $indent--;
        $out .= $arr[$x];
        //do the last 4 letters spell FROM?
        if(substr($out, $x-3, $x) == 'FROM') {
            if($indent == 0) { //not anywhere within parens
                $start = $x+2;
                break; //go no further 
            }
        }
    }
    //everything after the first occurrence of FROM
    return substr($sql, $start);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM