代码之家  ›  专栏  ›  技术社区  ›  adopilot

MS-SQL中的正则表达式

  •  1
  • adopilot  · 技术社区  · 16 年前

    我对Regex了解不多,我想尝试根据流动指令从数据库解析sting。

    表中的数据看起来像

    create table #tempTBL (opis varchar(40))
    go
    insert into #tempTBL
    select 'C 136'
    union 
    select 'C 145'
    union 
    select 'C146'
    union 
    select 'AK C 182'
    union 
    select 'C  277'
    union 
    select 'C-240'
    union 
    select 'ISPRAVKA PO C 241'
    

    选择sting看起来像

    Select 
         reverse(
                rtrim(
                        ltrim(
                                replace(
                                        (substring
                                                (reverse(opis)
                                                        ,0
                                                        ,charindex(
                                                                    'C',reverse(opis)
                                                                   )
                                                )
                                          )
                                ,'-',' ')
                              )
                      )
                ) as jci
    from #tempTBL
    

    如果我用regex重复这个过程,我的C代码应该是什么样子

    3 回复  |  直到 11 年前
        1
  •  1
  •   Ed Harper    16 年前

    有很多例子,但是 this article 是一个很好的开始

    编辑 (\d+) (表示作为匹配组返回的一个或多个连续数字)。

        2
  •  1
  •   particle    16 年前

    看到这个了吗 article

        3
  •  1
  •   VladV    16 年前

    使用CLR regex可能会相当慢。如果转换像示例中那样简单,那么最好使用简单SQL。

    看看PATINDEX函数,可能有用。

    create function dbo.ParseNum(@s varchar(40)) returns char(3)
    as begin
        declare @n int
        set @s = replace(replace(@s, '-', ''), ' ', '')
        set @n = patindex('%C[0-9][0-9][0-9]', @s)
        if @n = 0 return null
        return substring(@s, @n+1, 3)
    end
    go
    
    select opis, dbo.ParseNum(opis) from #tempTBL