【问题标题】:How can I escape characters (, ), [, ], *, _, with \ without changing link construction: []()如何在不更改链接结构的情况下使用 \ 转义字符 (、)、[、]、*、_、:[]()
【发布时间】:2021-12-08 09:23:13
【问题描述】:

我有一个问题,例如我有一个文本:

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\]"

如何确保链接 []() 的设计不会改变?即它看起来像:

desired output:"text, \*text\*, text, text, \(text\), \[text\], [some\_text with \_ \*](http://.....) \*text\*, text, text, \(text\), \[text\]"

【问题讨论】:

  • 您的正则表达式是否匹配您需要转义的所有字符?是否与Escaped character on Telegram Bot API 4.5 MarkdownV2 gives trouble for hyper link有关
  • @WiktorStribiżew,我没有写所有字符,因为我试图通过链接解决问题,但我不太明白如何解决。我试过: (? . *) ] \ ((? . *)) ([| * {} # + = \ -_.! ~> `]),但是它仍然像这样工作:\ [... \] \ (url \)
  • 请在代码周围使用反引号格式化问题。目前尚不清楚什么是逃逸的,什么不是。检查我的示例编辑。
  • @WiktorStribiżew,我修正了格式,谢谢你的例子

标签: c# regex markdown


【解决方案1】:

你需要匹配并捕获markdown链接部分,只匹配你需要转义的字符,然后在替换部分使用匹配评估器:

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 组,然后是除 [] 之外的零个或多个字符(使用 [^][]*),然后是 ] 字符、(,然后是零个或多个其他字符比()(和[^()]*)然后是) 字符
  • | - 或
  • [][()*_] - 匹配的字符类:](注意它没有转义,因为它是字符类中的第一个字符)、[()*_字符。

m =&gt; m.Groups[1].Success ? m.Groups[1].Value : $@"\{m.Value}" 替换如果第 1 组匹配,则将找到的匹配替换为第 1 组值,否则,替换为带有 \ 前缀的匹配值(字符类中定义的特殊字符)。

【讨论】:

  • 非常感谢,帮了我很大的忙,但是比如链接的文字有相同的符号,怎么转义,[Hello_World*](url)([Hello_World *](网址)?
  • @di_va 然后使用var pattern = @"\[([^][]*)]\(([^()]*)\)|[][()*_]"; 然后m =&gt; m.Groups[1].Success ? $@"[{Regex.Replace(m.Groups[1].Value, @"[()_*]", @"\$&amp;")}]({Regex.Replace(m.Groups[2].Value, @"[()_*]", @"\$&amp;")})" : $@"\{m.Value}")
  • 我可以问一个问题吗?我输入了 [text - # { } ](url) 字符:#, {, } - 但它没有逃脱它,为什么?并将这个字符添加到模式中
  • @di_va 这取决于您“放置”它的位置。必须是[][()*_-]
  • 我把它放在最后一个结构 [][(){}*_|#+=.!\-~>] 但他们没有逃跑
猜你喜欢
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 2021-09-22
  • 1970-01-01
相关资源
最近更新 更多