【问题标题】:PatIndex Pattern /Regex: How to match a dot followed by a spacePatIndex Pattern /Regex:如何匹配点后跟空格
【发布时间】:2016-02-12 09:13:20
【问题描述】:

Q1-PatIndex 模式正则表达式:如何匹配点后跟空格? Q2 -PatIndex Pattern Regex:如何匹配一个点后跟两个空格?

我想把它放在这里只得到目标内容

 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

【问题讨论】:

  • \.\s (Q1) 或 \.\s{2} (Q2)。罗杰出去 :)
  • 在广阔的世界中有大量的教程和在线测试表格。 SO 不是作业平台...
  • 预期输出是什么?
  • 更新问题@RahulTripathi
  • @PhilipMorris:- 更新了我的答案。请检查。

标签: sql-server regex patindex


【解决方案1】:

这个呢:

简短的解释:用 xml-tags 替换 . 会将该字符串“拆分”成与您的字符串一样多的“部分”。 XML-value 方法将获取第一项的值,即字符串直到第一个 .

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    

【讨论】:

  • 我得到了 Lalallaa 目标:这是真的喵喵,Lalallaa 目标:这是真的,lALALLA 目标:这是真的
  • @PhilipMorris,这很简单,只需使用您自己的substring 方法切断开头,编辑我的答案...
  • 有没有可能它不适用于中文字符或特殊字符?我收到错误 XML 解析:非法名称字符
  • @PhilipMorris 您可能必须将所有变量声明为 NVARCHAR 并在所有字面上写的字符串 (N'Your string here') 中加上“N”以使其成为 unicode...
  • 我确认了,类型是ntext
【解决方案2】:

您也可以尝试使用 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 

【讨论】:

  • 我得到了目标:这是真理喵。,目标:这是真理,目标:这是真理
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
相关资源
最近更新 更多