Regular expression to replace square brackets with angle brackets

前端 未结 3 453
Happy的楠姐
Happy的楠姐 2021-01-28 19:01

I have a string like:

[a b=\"c\" d=\"e\"]Some multi line text[/a]

Now the part d=\"e\" is optional. I want to convert such type of

3条回答
  •  一生所求
    2021-01-28 19:20

    For HTML tags, please use HTML parser.

    For [a][/a], you can do like following

    Match m=Regex.Match(@"[a b=""c"" d=""e""]Some multi line text[/a]", 
                        @"\[a b=""([^""]+)"" d=""([^""]+)""\](.*?)\[/a\]",
                        RegexOptions.Multiline);
    
    m.Groups[1].Value
    "c"
    m.Groups[2].Value
    "e"
    m.Groups[3].Value
    "Some multi line text"
    

    Here is Regex.Replace (I am not that prefer though)

    string inputStr = @"[a b=""[[[[c]]]]"" d=""e[]""]Some multi line text[/a]";
    string resultStr=Regex.Replace(inputStr,
                                @"\[a( b=""[^""]+"")( d=""[^""]+"")?\](.*?)\[/a\]",
                                @"$3", 
                                RegexOptions.Multiline);
    

提交回复
热议问题