正则表达式用“et al”替换第二个逗号之后的所有内容

问题描述 投票:0回答:2

当特定书籍的作者太多时,我尝试解析一些文本(作者姓名)以替换第二个逗号之后的所有内容。

示例:

Michel Galarneau, Jean Valjean, Michel Tremblay, Martin St-Louis

将在字符串操作之后:

Michel Galarneau, Jean Valjean, et al.

太胖了,我能够捕捉到我想要替换的部分,但我不确定这是要走的路......

(?:[^,]*,\s*){2}(.*)

选择“Marc St-Pierre, Yvon Sabon”组,我想将其替换为“et al.”。

感谢您的帮助!

sql sql-server regex string replace
2个回答
0
投票

这只是使用一点

JSON
concat()
的另一种选择,它将
NULLs
视为空字符串。

请注意,如果两个或更少,则出现

no et al

示例

Declare @YourTable Table ([SomeCol] varchar(150))  Insert Into @YourTable Values 
 ('Michel Galarneau, Jean Valjean, Michel Tremblay, Martin St-Louis'),
 ('Author 1of2, Author 2of2'),
 ('Author 1of1')
 
Select A.SomeCol
      ,NewVal = JSON_VALUE(JS,'$[0]')
                + concat('',', '+JSON_VALUE(JS,'$[1]'))
                + concat('',left(JSON_VALUE(JS,'$[2]'),0)+', et al')
From @YourTable A
Cross Apply (values ('["'+replace(string_escape([SomeCol],'json'),',','","')+'"]') ) B(JS)    

结果

SomeCol                                                             NewVal
Michel Galarneau, Jean Valjean, Michel Tremblay, Martin St-Louis    Michel Galarneau,  Jean Valjean, et al
Author 1of2, Author 2of2                                            Author 1of2,  Author 2of2
Author 1of1                                                         Author 1of1

-1
投票

您可以使用 SQL Server 中的简单字符串函数来完成此操作:

CREATE FUNCTION dbo.ufnTruncateAuthorList(@AuthorList varchar)
RETURNS varchar
AS
  BEGIN
    DECLARE @FirstComma int, @SecondComma int, @Result varchar;

    -- locate offset of the first comma
    SET @FirstComma = CHARINDEX(',', @AuthorList);
    -- locate offset of the second comma
    SET @SecondComma = CHARINDEX(',', @AuthorList, @FirstComma + 1);

    -- substring + concat only if more than one comma found
    IF @FirstComma = 0 OR @SecondComma = 0
        SET @Result = @AuthorList;
    ELSE
        SET @Result = CONCAT(SUBSTRING(@AuthorList, 0, @SecondComma), ', et al.');
    RETURN @Result;
  END

然后你可以这样做:

SELECT dbo.ufnTruncateAuthorList('Michel Galarneau, Jean Valjean, Michel Tremblay, Martin St-Louis')
© www.soinside.com 2019 - 2024. All rights reserved.