Search code examples
sql-serverregexpatindex

PatIndex Pattern /Regex: How to match a dot followed by a space


Q1-PatIndex Pattern Regex: How to match a dot followed by a space? Q2 -PatIndex Pattern Regex: How to match a dot followed by two spaces?.

I want to put it in here to get only the GOAL content

 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

Expected Output

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

I used Shnugos answer on the real DB and I encountered an error : Illegal name character

I checked the data type , it is ntext


Solution

  • What about this:

    Short explanation: Replacing . with xml-tags will "split" this string in as many "parts" as there are in your string. The XML-value method will take the first item's value which is the string up to the first .

    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