如何替换字符串中的奇数模式? [英] How I can replace odd patterns inside a string?
问题描述
我正在用SQL创建一个临时过程,因为我有一个用markdown编写的表的值,因此它在Web浏览器中显示为呈现的HTML.(将markdown转换为HTML).
I'm in the process of creating a temporary procedure in SQL because I have a value of a table which is written in markdown, so it appear as rendered HTML in the web browser (markdown to HTML conversion).
该列的字符串当前如下所示:
String of the column currently look like this:
Questions about **general computing hardware and software** are off-topic for Stack Overflow unless they directly involve tools used primarily for programming. You may be able to get help on [Super User](http://superuser.com/about)
我目前正在处理粗体和斜体文本.这意味着(对于粗体文本而言)我将需要将模式**
的奇数N替换为<b>
,将偶数替换为</b>
.
我看到了 replace(),但是它对字符串.
I'm currently working with bold and italic text. This mean (in the case of bold text) I will need to replace odd N times the pattern**
with<b>
and even times with</b>
.
I saw replace() but it perform the replacement on all the patterns of the string.
那么,仅当它是奇数还是偶数时,才如何替换子字符串?
So How I can replace a sub-string only if it is odd or only it is even?
更新: 有些人想知道我使用的是哪种架构,所以请看一下 如果需要,还可以添加一个额外的 :标记为HTML的超链接的markdown样式看起来并不那么简单.
One more extra if you want: The markdown style hyperlink to html hyperlink doesn't look so simple.
推荐答案
使用STUFF
函数和简单的WHILE
循环:
Using theSTUFF
function and a simpleWHILE
loop:
CREATE FUNCTION dbo.fn_OddEvenReplace(@text nvarchar(500),
@textToReplace nvarchar(10),
@oddText nvarchar(10),
@evenText nvarchar(500))
RETURNS varchar(max)
AS
BEGIN
DECLARE @counter tinyint
SET @counter = 1
DECLARE @switchText nvarchar(10)
WHILE CHARINDEX(@textToReplace, @text, 1) > 0
BEGIN
SELECT @text = STUFF(@text,
CHARINDEX(@textToReplace, @text, 1),
LEN(@textToReplace),
IIF(@counter%2=0,@evenText,@oddText)),
@counter = @counter + 1
END
RETURN @text
END
您可以像这样使用它:
SELECT dbo.fn_OddEvenReplace(column, '**', '<b>', '</b>')
FROM table
更新:
这被重写为SP:
CREATE PROC dbo.##sp_OddEvenReplace @text nvarchar(500),
@textToReplace nvarchar(10),
@oddText nvarchar(10),
@evenText nvarchar(10),
@returnText nvarchar(500) output
AS
BEGIN
DECLARE @counter tinyint
SET @counter = 1
DECLARE @switchText nvarchar(10)
WHILE CHARINDEX(@textToReplace, @text, 1) > 0
BEGIN
SELECT @text = STUFF(@text,
CHARINDEX(@textToReplace, @text, 1),
LEN(@textToReplace),
IIF(@counter%2=0,@evenText,@oddText)),
@counter = @counter + 1
END
SET @returnText = @text
END
GO
并执行:
DECLARE @returnText nvarchar(500)
EXEC dbo.##sp_OddEvenReplace '**a** **b** **c**', '**', '<b>', '</b>', @returnText output
SELECT @returnText
这篇关于如何替换字符串中的奇数模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!