Finding text between tags and replacing it along with the tags

前端 未结 3 432
日久生厌
日久生厌 2021-01-07 00:00

I am using The following regex pattern to find text between [code] and [/code] tags:

(?<=[code]).*?(?=[/code])

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 00:45

    I would use a HTML Parser for this. I can see that what you are trying to do is simple, however these things have a habit to get much more complicated overtime. The end result is much pain for the poor sole who has to maintain the code in the future.

    Take a look at this question about HTML Parsers
    What is the best way to parse html in C#?

    [Edit]
    Here is a much more relevant answer to the question asked. @Milad Naseri regex is correct you just need to do something like

    string matchCodeTag = @"\[code\](.*?)\[/code\]";
    string textToReplace = "[code]The Ape Men are comming[/code]";
    string replaceWith = "Keep Calm";
    string output = Regex.Replace(textToReplace, matchCodeTag, replaceWith);
    

    Check out this web sites for more examples
    http://www.dotnetperls.com/regex-replace
    http://oreilly.com/windows/archive/csharp-regular-expressions.html

    Hope this helps

提交回复
热议问题