简体   繁体   中英

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. The issue is that I'm trying to do a replace on the hash marks so they don't appear in the HTML output. 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. 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).

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.

Is there a better tool for the job than 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. Thus your .Replace("#", "") is doing nothing. The regular expression then replaces the two occurrences of "$1" in the output of MakeLink with the first capture group.

If you replace "$1" with "$2" then I think you get the result you want, just not quite in the manner you're expecting.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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