[英]How to extract a substring between two characters in a string having undetermined pattern in SQL
I have read a lot of topics discussing extracting substring between two characters but my problem is a bit different than the existing ones.我已经阅读了很多讨论在两个字符之间提取 substring 的主题,但我的问题与现有问题有点不同。 I have a string like this with different patterns ''' /m/ hello end;
我有一个这样的字符串,具有不同的模式 ''' /m/ hello end; /r/ how are you end;
/r/你过得怎么样; '''
'''
I need to separate strings between /m/ and end;我需要在 /m/ 和 end 之间分隔字符串; and between /r/ and end;
在 /r/ 和 end 之间;
I have used substring and charindex functions which give correct output BUT NOT in all cases of input string.我使用了 substring 和 charindex 函数,它们给出了正确的 output 但并非在所有输入字符串的情况下。 My input string has too many variation.eg it could be like ''' /m/ hello /r/ how are you end;
我的输入字符串有太多变化。例如,它可能像''' /m/ hello /r/ 你好吗? (no end in /m/ part) ''' in this case if I extract string between /m/ and end;
(在 /m/ 部分没有结尾)''' 在这种情况下,如果我在 /m/ 和 end 之间提取字符串; it will include /r/ which I don't need.
它将包括我不需要的 /r/ 。 if I change the logic and extract between /m/ and /r/ then /r/ could be before /m/ eg
如果我更改逻辑并在 /m/ 和 /r/ 之间提取,则 /r/ 可能在 /m/ 之前,例如
''' /r/ I am working from home during this pandemic end; ''' /r/ 在大流行结束期间我在家工作; /m/ how about you end;
/m/ 你怎么结束; /r/ before /m/) ''' input string has nor definite length.
/r/ before /m/) ''' 输入字符串没有确定的长度。
Tried to use PATINDEX but my input string has no specific pattern.尝试使用 PATINDEX 但我的输入字符串没有特定模式。
I need expert's advice.我需要专家的建议。
Thanks for your help!谢谢你的帮助!
This splits the string by replacing both /m/ and /r/ with a pipe '|'这通过将 /m/ 和 /r/ 替换为 pipe '|' 来拆分字符串and then using STRING_SPLIT on the result.
然后在结果上使用 STRING_SPLIT 。
declare @string varchar(100)=''' /m/ hello end; /r/ how are you end; ''';
select @string=replace(@string, t.v, '|')
from
(values ('/m/'), ('/r/')) t(v);
select trim([value]) split_string from string_split(@string, '|');
UPDATED: To retain the two search terms inside @string it uses nested REPLACE functions.更新:为了在 @string 中保留两个搜索词,它使用嵌套的 REPLACE 函数。 To retain the ordering of the appearance of the search terms I used this splitter.
为了保留搜索词的外观顺序,我使用了这个拆分器。
declare @string varchar(100)=''' /m/ hello end; /r/ how are you end; ''';
select * from dbo.DelimitedSplit8K(replace(replace(@string,'/m/', '|/m/'),'/r/', '|/r/'), '|');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.