查找正则表达式并替换特定字符
问题描述:
我需要在字符串中找到一个数字值+引号(示例5“)。一旦找到,我需要用”磅“替换引号。串查找正则表达式并替换特定字符
Work and run with Joe "The King" Mel using a 3" vest with "Dog-Bone" weights.
我已经试过
SELECT REPLACE(REPLACE('Work and run with Joe "The King" Mel using a 3" vest with "Dog-Bone" weights.', '%[^0-9]"%', 'pound'), '"', 'pound')
但是它与“英镑”替换所有的报价。
答
这将找到一个数字,后跟一个"
的第一次出现,并与pound
取代"
。
declare @s varchar(100)
set @s = 'Work and run with Joe "The King" Mel using a 3" vest with "Dog-Bone" weights.'
select stuff(@s, patindex('%[0-9]"%', @s)+1, 1, ' pound')
如果你有多个,你可以把它放在一个while循环。
while patindex('%[0-9]"%', @s) > 0
begin
set @s = stuff(@s, patindex('%[0-9]"%', @s)+1, 1, ' pound')
end
答
如果你不能表达你想要的变化确定性算法做出来,你永远无法写出一个正则表达式作为一个实现。
你已经写了两个替换表达式:一个在数字后面只替换引号,但另一个替换所有引号,句点。
+0
我试图代码,以查找包含在正则表达式“%[^ 0-9]“%引号的位置,然后做该特定字符位置的更换,但没有工作.. – 2011-12-30 18:04:00
的伟大工程。 ..用PATINDEX默认值0修正了一些错误。 – 2011-12-30 19:02:43