使用 PATINDEX 在 SQL 服务器中使用多种格式的文本中查找时间

Using PATINDEX to find times within text in SQL Server using multiple formats

我需要使用 return 格式时间 12:43 和 1:33 的正则表达式,我尝试了以下方法,每个 return 都是想要的结果,我怎样才能将两者结合起来,所以 SQL 可以 return 第一个或第二个 :

set @reg = '[0-9]:[0-5][0-9]'
set @reg = '[0-1][0-2]:[0-5][0-9]'

我尝试过的:

Declare @reg nvarchar(100) 
set @reg = '[0-9]:[0-5][0-9]' 
--set @reg = '[0-1][0-2]:[0-5][0-9]' 

select remarks, 
       substring(remarks,PATINDEX('%' + @reg + '%',remarks) ,5), len(PATINDEX('%' + @reg + '%',remarks)) 
from infraction 
where remarks like '%' + @reg + '%'

您需要找到任何存在任一模式的行,然后根据匹配的模式应用适当的 SQL 限制 "regex"。 HH:MMH:MM 限制更多,所以我们用它来检查。

CREATE TABLE #infraction (
  Comment VARCHAR(100)
)

INSERT INTO #infraction VALUES ('time of 12:35 incident')
INSERT INTO #infraction VALUES ('time of 1:34 incident');

DECLARE @reg NVARCHAR(100) = '[0-9]:[0-5][0-9]'
DECLARE @reg2 NVARCHAR(100) = '[0-1][0-2]:[0-5][0-9]'

SELECT
    Comment,
    IIF(PATINDEX('%' + @reg2 + '%', Comment) = 0,
        SUBSTRING(Comment, PATINDEX('%' + @reg + '%', Comment), 4),
        SUBSTRING(Comment, PATINDEX('%' + @reg2 + '%', Comment), 5)
    )
FROM
    #infraction 
WHERE
    Comment LIKE '%' + @reg + '%'
    or
    Comment LIKE '%' + @reg2 + '%';

Returns:

12:35
1:34

SQL Fiddle