MySql-RegEx提取变量的数字序列

时间:2019-01-17 14:32:16

标签: mysql regex

我有这张桌子:

DROP TABLE IF EXISTS test2_sim;
CREATE TABLE test2_sim (
texto VARCHAR(1024) NOT NULL
);

具有以下记录:

INSERT INTO test2_sim (texto) VALUES ('/A/posts/2088973241125818');
INSERT INTO test2_sim (texto) VALUES ('/A/posts/2088973241125818?commen');
INSERT INTO test2_sim (texto) VALUES ('/B/posts/10155759853867175?__xts_');
INSERT INTO test2_sim (texto) VALUES ('/C/posts/595673157521288');
INSERT INTO test2_sim (texto) VALUES ('/D/posts/365108183946?__xts__%5B0%5D=68.ARCs');
INSERT INTO test2_sim (texto) VALUES ('/E/posts/1028007200735853?__xts__%5B0%5');

我正在尝试为每条记录提取可变的数字序列, 例如

Record1 > 2088973241125818
Record2 > 2088973241125818
Record3 > 10155759853867175

是否可以在Select语句中使用REGEX命令? 喜欢:

Select *, REGEX(texto,'^[specific_patterns]' AS regex_out from test2_sim;

让我们假设一个有效的数字序列是连续的数字> 10。

非常感谢 注册表

2 个答案:

答案 0 :(得分:2)

无需使用REGEX。用CONVERTSUBSTRING_INDEX用这种方式怎么样?

SELECT CONVERT(SUBSTRING_INDEX(texto, '/', -1), UNSIGNED INTEGER) as seq_num from test2_sim;

请参阅小提琴: http://www.sqlfiddle.com/#!9/e914d/12

答案 1 :(得分:1)

此查询向您显示如何在不使用REGEX的情况下“解析”数字。

查询

SELECT 
 *
 , CAST(
     REVERSE(
        SUBSTRING_INDEX(
            REVERSE(texto)
          , '/'
          , 1
        )
     ) AS UNSIGNED)
FROM 
 test2_sim

结果

| texto                                        | CAST(REVERSE(SUBSTRING_INDEX(REVERSE(texto), '/', 1)) AS UNSIGNED) |
| -------------------------------------------- | ------------------------------------------------------------------ |
| /A/posts/2088973241125818                    | 2088973241125818                                                   |
| /A/posts/2088973241125818?commen             | 2088973241125818                                                   |
| /B/posts/10155759853867175?__xts_            | 10155759853867175                                                  |
| /C/posts/595673157521288                     | 595673157521288                                                    |
| /D/posts/365108183946?__xts__%5B0%5D=68.ARCs | 365108183946                                                       |
| /E/posts/1028007200735853?__xts__%5B0%5      | 1028007200735853                                                   |

请参阅demo