有这么一个字符串,if(4/(if(2>1,2,1)+2) = 0,if(6/(3+3)=1,3,2),4/(4+4))
,怎么把他里面的 和if左括号 匹配的 右小括号 都变成 右中括号。
处理前:if(4/(if(2>1,2,1)+2) = 0,if(6/(3+3)=1,3,2),4/(4+4))
处理后:if(4/(if(2>1,2,1]+2) = 0,if(6/(3+3)=1,3,2],4/(4+4)]
项目里很重要的一个功能,各位高手帮帮忙啊,谢了
sql?字符串处理?
------解决方案--------------------
--仅供参考啊,汗~,期待好的算法……
--还是用程序实现比较方便。用CLR写个函数,放到SQL SERVER里来处理吧,最简单。
DROP TABLE #temp
CREATE TABLE #temp(id INT, expression VARCHAR(MAX))
INSERT #temp values(1, 'if(4/(if(2>1,2,1)+2) = 0,if(6/(3+3)=1,3,2),4/(4+4))')
--SQL
;WITH cte1 AS
(
SELECT
id,
pos = CHARINDEX('(', expression),
word = CAST(LEFT(expression, CHARINDEX('(', expression) - 1) AS NVARCHAR(MAX)),
name = 1,
Split = CAST(STUFF(expression + '(', 1, CHARINDEX('(', expression + '('), '') AS NVARCHAR(MAX))
FROM #temp
UNION ALL
SELECT
id,
pos = a.pos + CHARINDEX('(', Split),
word = CAST(LEFT(Split, CHARINDEX('(', Split) - 1) AS NVARCHAR(MAX)),
name = 1,
Split = CAST(STUFF(Split, 1, CHARINDEX('(', Split), '') AS NVARCHAR(MAX))
FROM cte1 a
WHERE Split > ''
),
cte2 AS
(
SELECT
id,
pos = CHARINDEX(')', expression),
word = CAST(LEFT(expression, CHARINDEX(')', expression) - 1) AS NVARCHAR(MAX)),
name = -1,
Split = CAST(STUFF(expression + ')', 1, CHARINDEX(')', expression + ')'), '') AS NVARCHAR(MAX))
FROM #temp
UNION ALL
SELECT
id,
pos = a.pos + CHARINDEX(')', Split),
word = CAST(LEFT(Split, CHARINDEX(')', Split) - 1) AS NVARCHAR(MAX)),
name = -1,
Split = CAST(STUFF(Split, 1, CHARINDEX(')', Split), '') AS NVARCHAR(MAX))