phpshellawksed

How to extract the last item from a table name in SQL using regex in PHP?


Question:

I have an SQL query in the format of:

SELECT dt FROM a.b.c WHERE dt = '20210808' LIMIT 10;

The table name in this SQL statement is a.b.c, and I want to extract only the last part of the table name (c). The table name always follows this pattern: schema1.schema2.table_name. My goal is to extract the table_name (the last item) using a regular expression in PHP.

Here’s my current attempt:

$sql = "SELECT dt FROM a.b.c WHERE dt = '20210808' LIMIT 10";
$tmp_table_name_pattern = '/\.([^.]*$)/';
preg_match_all($tmp_table_name_pattern, $sql, $match);
print_r($match);

However, the result I get is:

Array (
    [0] => Array (
        [0] => .c WHERE dt = '20210808' LIMIT 10
    )
    [1] => Array (
        [0] => c WHERE dt = '20210808' LIMIT 10
    )
)

What I expect is to extract only c as the table name. How can I modify my regular expression or PHP code to achieve this?

What I've tried:

Expected result:

I want the output to be:

Array (
    [0] => Array (
        [0] => c
    )
)

Solution

  • does the regular expression is different between various environments like SHELL、 PHP、JAVA, etc?

    Yes, they do differ. Term flavour is used to denote particular version. Examples are

    If you are interested in flavour used in particular programming language please refer to Regular Expression Engine Comparison Chart