lundi 6 avril 2020

Java regex doesn't match

I have this regex:

#(?<=[^\w`"\[?:]|^)[a-z_][a-z0-9_]*(?=[^\w`"(\]]|$)#Di

and I'm trying to make SQL syntax pretty. For example from "SELECT * FROM users WHERE username=?;" to

SELECT * FROM `users` WHERE `username`=?;

This regex matching all words, which doesn't contain backticks. And in the match group I'm checking if is matched word uppercase. If is it true, then this word is skipped. And other words are added to the backticks. My problem is, that regex doesn't match nothing. I have similar code in the PHP, and it works there.

function tryDelimite(string $s): string {
    return preg_replace_callback('#(?<=[^\w`"\[?:]|^)[a-z_][a-z0-9_]*(?=[^\w`"(\]]|$)#Di', function (array $m): string {
        return strtoupper($m[0]) === $m[0] ? $m[0] : delimite($m[0]);
    }, $s);
}

function delimite(string $name): string {
    return '`' . str_replace('`', '``', $name) . '`';
}

echo tryDelimite("SELECT * FROM users WHERE username=?;");

Does anyone have an idea, please?

Aucun commentaire:

Enregistrer un commentaire