Finding text between tags and replacing it along with the tags

前端 未结 3 430
日久生厌
日久生厌 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:36

    You need to use back referencing, i.e. replace \[code\](.*?)\[/code\] with something like <code>$1</code> which will give you what's been enclosed by the [code][/code] tags enclosed in -- for this example -- <code></code> tags.

    0 讨论(0)
  • 2021-01-07 00:37

    Use this:

    var s = "My temp folder is: [code]Path.GetTempPath()[/code]";
    
    var result = Regex.Replace(s, @"\[code](.*?)\[/code]",
        m =>
            {
                var codeString = m.Groups[1].Value;
    
                // then you have to evaluate this string
                return EvaluateMyCode(codeString)
            });
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题