简体   繁体   English

正则表达式替换字符串函数无法正常工作

[英]Regex replace string function not working as expected

I'm trying to implement a hashtag function in a web app to easily embed search links into a page. 我正在尝试在Web应用程序中实现主题标签功能,以轻松地将搜索链接嵌入到页面中。 The issue is that I'm trying to do a replace on the hash marks so they don't appear in the HTML output. 问题是我正在尝试对哈希标记进行替换,以使它们不会出现在HTML输出中。 Since I'm also wanting to be able to also have hash marks in the output I can't just do a final Replace on the entire string at the end of processing. 由于我还希望在输出中也包含哈希标记,因此我不能只在处理结束时对整个字符串进行最终的Replace I'm going to want to be able to escape some hash marks like so \\#1 is my answer and I'd find and replace the \\# with just # but that is another problem that I'm not even ready for (but still thinking of). 我会希望能够逃脱,像这样一些哈希标记\\#1 is my answer ,我会发现并更换\\#只有#但是这就是我甚至准备好另一个问题(但还在想)。

This is what I have so far mocked up in a console app, 到目前为止,这是我在控制台应用程序中模拟的内容,

static void Main(string[] args)
{
    Regex _regex = new Regex(@"(#([a-z0-9]+))");
    string link = _regex.Replace("<p>this is #my hash #tag.</p>", MakeLink("$1"));
}
public static string MakeLink(string tag)
{
    return string.Format("<a href=\"/Search?t={0}\">{1}</a>", tag.Replace("#", ""), tag);
}

The output being: 输出为:
<p>this is <a href="/Search?t=#my">#my</a> hash <a href="/Search?t=#tag">#tag</a>.</p>

But when I run it with breaks while it's running MakeLink() it's string is displayed at "$1" in the debugger output and it's not replacing the hash's as expected. 但是,当我在运行MakeLink()时使用断点运行它时,它的字符串显示在调试器输出中的"$1" ,并且没有按预期替换哈希。

Is there a better tool for the job than regex? 有没有比regex更好的工作工具? Or can I do something else to get this working correctly? 还是我可以做些其他的事情来使它正常工作?

Note that you're passing a literal "$1" into MakeLink, not the first captured group. 请注意,您要向MakeLink(而不是第一个捕获的组)传递文字“ $ 1”。 Thus your .Replace("#", "") is doing nothing. 因此,您的.Replace(“#”,“”)无所事事。 The regular expression then replaces the two occurrences of "$1" in the output of MakeLink with the first capture group. 然后,正则表达式用第一个捕获组替换MakeLink输出中出现的两次“ $ 1”。

If you replace "$1" with "$2" then I think you get the result you want, just not quite in the manner you're expecting. 如果您将“ $ 1”替换为“ $ 2”,那么我认为您将获得所需的结果,只是不完全符合您的预期。

To not replace your escaped hashtags, just modify your current regex to not match anything that starts with an escape: 要不替换转义的主题标签,只需修改当前的正则表达式,使其与以转义开头的任何内容都不匹配:

Regex _regex = new Regex(@"[^\\](#([a-z0-9]+))");

And then apply a new regex to find only escaped hashtags and replace them with unescaped ones: 然后应用新的正则表达式以仅查找转义的井号并将其替换为未转义的井号:

Regex _escape = new Regex(@"\\(#([a-z0-9]+))");
_escape.Replace(input, "$1");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM