使用tsql,从第60个字符开始获取字符串的正确部分,但不要分解单词

bxgwgixi  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(265)

我试图将长字符串(>60个字符)分成两部分,但要保持包含第60个字符的单词的完整性。
例如,对于字符串 one two three four five six seven eight nine ten eleven twelve thirteen fourteen ,这封信 l 在世界上 twelve 是第60个字符,所以我想把字符串分解为 one two three four five six seven eight nine ten eleventwelve thirteen fourteen 到目前为止,专注于获得字符串的正确部分,我可以使用 REVERSE() 最后一句话

DECLARE @Input varchar(100)
SET @Input = 'one two three four five six seven eight nine ten eleven twelve thirteen fourteen'

SELECT LTRIM(RTRIM(RIGHT(@Input, CHARINDEX(' ', REVERSE(@Input)) - 1))) AS LastWholeWord
    ,  @Input           AS UnalteredString
    ,  LEN(@Input)      AS LengthOfString
    ,  LEFT(@Input, 60) AS First60

现在,我的想法是我可以限制最后 REVERSE() 前60个字符 LEFT(@Input, 60) 就其本身而言 LTRIM(RTRIM(RIGHT(@Input, CHARINDEX(' ', REVERSE(LEFT(@Input, 60))) - 1))) 但这似乎没有达到预期的效果。如果有人能给我指出正确的方向,我会很高兴的!!
谢谢你的时间!

pu3pd22g

pu3pd22g1#

这应该起作用:

DECLARE @divingSpaceChar INT =
LEN(SUBSTRING(@Input,0, 60)) - CHARINDEX(' ', REVERSE(SUBSTRING(@Input,0, 60))) + 1

SELECT SUBSTRING(@Input, 0, @divingSpaceChar) AS leftString
SELECT LTRIM(SUBSTRING(@Input,  @divingSpaceChar, LEN(@input))) AS rightString

获取子字符串前60个字符中最后一个空格字符的索引。从最后一个charindex获取子字符串。。。
如果没有其他变量,可以执行以下操作:

SELECT
RTRIM(LTRIM(SUBSTRING(@Input, LEN(SUBSTRING(@Input,0, 60)) 
- CHARINDEX(' ', REVERSE(SUBSTRING(@Input,0, 60)))+ 1, LEN(@input)))) AS RightPart,
RTRIM(LTRIM(SUBSTRING(@Input, 0, LEN(SUBSTRING(@Input,0, 60))
- CHARINDEX(' ', REVERSE(SUBSTRING(@Input,0, 60)))+ 1))) AS LeftPart
b91juud3

b91juud32#

使用正则表达式怎么样,看起来干净多了。。
(我将使用presto显示语法,但我假设与其他sql非常相似)
正则表达式: '(.{1,60})(?= )(.*)' .
在查询中注意:$1,$2显示字符串的每个部分。。

SELECT regexp_replace('one two three four five six seven eight nine ten eleven twelve thirteen fourteen',
                  '(.{1,60})(?= )(.*)', '$1') part1,
       regexp_replace('one two three four five six seven eight nine ten eleven twelve thirteen fourteen',
                  '(.{1,60})(?= )(.*)', '$2') part2

-----
Results
part1                                                    part2
one two three four five six seven eight nine ten eleven  twelve thirteen fourteen

相关问题