如何在不更改 link 结构的情况下使用 \ 转义字符 (, ), [ ], *, _: []()
How can I escape characters (, ), [, ], *, _, with \ without changing link construction: []()
我有以下文字:
input = "text, *text*, text, text, (text), [text], [text](http://.....) *text*, text, text, (text), [text]"
我正在尝试将字符“_”、“*”、“[”、“]”、“(”、“)”替换为“\_”、“\*”等
我正在写:
pattern = @"(?<!\[(?<text>.*)\]\((?<url>.*))([[\]\(\)*_])";
input = Regex.Replace(input, pattern, @"$1");
System output: "text, \*text\*, text, text, \(text\), \[text\], \[some\_text with \_ \* \]\(http://.....) \*text\*, text, text, \(text\), \[text\]"
如何确保 link []() 的设计不会改变?即它看起来像:
desired output:"text, \*text\*, text, text, \(text\), \[text\], [some\_text with \_ \*](http://.....) \*text\*, text, text, \(text\), \[text\]"
你需要匹配并捕获markdown link部分,只匹配你需要转义的字符,然后在替换部分使用匹配评估器:
var input = "text, *text*, text, text, (text), [text], [some_text with _*](http://.....) *text*, text, text, (text), [text]";
var pattern = @"(\[[^][]*]\([^()]*\))|[][()*_]";
Console.WriteLine(Regex.Replace(input, pattern, m =>
m.Groups[1].Success ? m.Groups[1].Value : $@"\{m.Value}"));
参见C# demo。 详情:
(\[[^][]*]\([^()]*\))
- 捕获组 1 匹配 [
,然后是 [
和 ]
以外的零个或多个字符(使用 [^][]*
),然后是]
字符,(
,然后是 (
和 )
以外的零个或多个字符(使用 [^()]*
),然后是 )
字符
|
- 或
[][()*_]
- 匹配的字符 class:]
(注意它没有转义,因为它是字符 class 中的第一个字符),[
、(
、)
、*
或 _
个字符。
如果第 1 组匹配,m => m.Groups[1].Success ? m.Groups[1].Value : $@"\{m.Value}"
替换将找到的匹配项替换为第 1 组值,否则,替换为匹配值(字符 class 中定义的特殊字符)与 \
前置。
我有以下文字:
input = "text, *text*, text, text, (text), [text], [text](http://.....) *text*, text, text, (text), [text]"
我正在尝试将字符“_”、“*”、“[”、“]”、“(”、“)”替换为“\_”、“\*”等
我正在写:
pattern = @"(?<!\[(?<text>.*)\]\((?<url>.*))([[\]\(\)*_])";
input = Regex.Replace(input, pattern, @"$1");
System output: "text, \*text\*, text, text, \(text\), \[text\], \[some\_text with \_ \* \]\(http://.....) \*text\*, text, text, \(text\), \[text\]"
如何确保 link []() 的设计不会改变?即它看起来像:
desired output:"text, \*text\*, text, text, \(text\), \[text\], [some\_text with \_ \*](http://.....) \*text\*, text, text, \(text\), \[text\]"
你需要匹配并捕获markdown link部分,只匹配你需要转义的字符,然后在替换部分使用匹配评估器:
var input = "text, *text*, text, text, (text), [text], [some_text with _*](http://.....) *text*, text, text, (text), [text]";
var pattern = @"(\[[^][]*]\([^()]*\))|[][()*_]";
Console.WriteLine(Regex.Replace(input, pattern, m =>
m.Groups[1].Success ? m.Groups[1].Value : $@"\{m.Value}"));
参见C# demo。 详情:
(\[[^][]*]\([^()]*\))
- 捕获组 1 匹配[
,然后是[
和]
以外的零个或多个字符(使用[^][]*
),然后是]
字符,(
,然后是(
和)
以外的零个或多个字符(使用[^()]*
),然后是)
字符|
- 或[][()*_]
- 匹配的字符 class:]
(注意它没有转义,因为它是字符 class 中的第一个字符),[
、(
、)
、*
或_
个字符。
如果第 1 组匹配,m => m.Groups[1].Success ? m.Groups[1].Value : $@"\{m.Value}"
替换将找到的匹配项替换为第 1 组值,否则,替换为匹配值(字符 class 中定义的特殊字符)与 \
前置。