替换字符串中的确切单词的多个实例

时间:2015-07-07 13:21:43

标签: sql postgresql pattern-matching

我在表格中有一个地址栏,我想要替换某个单词。但我的查询也取代了部分匹配:

select replace('the bthe the them', 'the', 'abc')

对于上面的例子,期望的输出应该是:

abc bthe abc them

但输出是:

abc babc abc abcm

如何解决这个问题?

4 个答案:

答案 0 :(得分:3)

select trim(replace(' the bthe the them ', ' the ', ' abc ')) 

答案 1 :(得分:2)

使用

SELECT regexp_replace('the bthe the them', '\ythe\y', 'abc','g')

\ y:表示字边界

标志g:用于替换所有出现的事件

答案 2 :(得分:0)

创建一个简单的函数如下:

CREATE FUNCTION [dbo].[fn_ReplaceCharacters]
(
    @String NVARCHAR(MAX),
    @MatchExpression VARCHAR(255),
    @Replace VARCHAR(255)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
    WHILE Charindex(@MatchExpression, @String)>0
       SET @String = REPLACE(@String, @MatchExpression, @Replace)
    RETURN @String
END
GO

然后引用它:

select dbo.fn_ReplaceCharacters('the bthe the them', 'the', 'abc')

返回结果:

abc babc abc abcm

答案 3 :(得分:-1)

List

输出:

SELECT REPLACE(' ' + column + ' ', ' the ', ' abc ')
FROM table

我假设您在替换字符串中的值时会从表中进行选择。所以'专栏'是您选择的表中的列,其中包含您要使用替换函数的值。

相关问题