PatIndex Pattern / Regex:如何匹配点后跟空格

时间:2016-02-12 09:13:21

标签: sql-server regex patindex

Q1-PatIndex Pattern Regex:如何匹配点后跟空格? Q2 -PatIndex Pattern Regex:如何匹配一个点后跟两个空格?

我想把它放在这里只获得GOAL内容

 Declare @Temp Table(Data VarChar(1000))

Insert Into @Temp Values('Lalallaa GOAL: This is the truthmeow. Meow.  ')
Insert Into @Temp Values('Lalallaa GOAL: This is the truth. Meowrwr. ')
Insert Into @Temp Values('lALALLA GOAL: This is the truth. Meowrwr.  NOTINCLUDED: WAWAW')


Select Left(
             SubString(Data,PATINDEX ('%GOAL%',Data), 8000) ,
             PatIndex('regex here', SubString(Data, PatIndex('%[GOAL]%', Data), 8000))-1)
From   @Temp

预期产出

GOAL: This is the truthmeow. 
GOAL: This is the truth.
GOAL: This is the truth. 

我在真正的数据库上使用了Shnugos答案,我遇到了一个错误:Illegal name character

我检查了数据类型,它是ntext

2 个答案:

答案 0 :(得分:1)

您也可以尝试使用LIKE语句。

columnname LIKE '.  %'

修改

试试这个:

Select SUBSTRING(data, LEN(LEFT(data, CHARINDEX ('GOAL:', data))) , LEN(data) - LEN(LEFT(data, CHARINDEX ('GOAL:', data))) - LEN(RIGHT(data, LEN(data) - CHARINDEX ('.', data))) - 1)
From   @Temp 

答案 1 :(得分:1)

这个怎么样:

简短说明:用{xml-tags替换.将"拆分"这个字符串在很多"部分"因为你的字符串中有。 XML值方法将获取第一个项的值,即第一个.

之前的字符串
Declare @Temp Table(Data VarChar(1000))

Insert Into @Temp Values('Lalallaa GOAL: This is the truthmeow. Meow.  ')
Insert Into @Temp Values('Lalallaa GOAL: This is the truth. Meowrwr. ')
Insert Into @Temp Values('lALALLA GOAL: This is the truth. Meowrwr. NOTINCLUDED: WAWAW')


Select CAST('<x>' + REPLACE(SubString(Data,PATINDEX ('%GOAL%',Data), 8000),'. ','</x><x>') + '</x>' AS XML).value('x[1]','varchar(max)')
From   @Temp