正则表达式来替换方括号用尖括号 [英] Regular expression to replace square brackets with angle brackets

查看:480
本文介绍了正则表达式来替换方括号用尖括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串:

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

现在部分 D =E是可选的。我想这种类型的字符串转换为:

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

<a b="c" d="e">Some multi line text</a>



A <$ C $的值C> b 和 D 是不变的,所以我并不需要赶上他们。我只需要的单位c 电子标记之间的文本并创建一个等价的XML为基础的表达。因此,如何做到这一点,因为有一些可选部分也。

The values of a b and d are constant, so I don't need to catch them. I just need the values of c, e and the text between the tags and create an equivalent xml based expression. So how to do that, because there is some optional part also.

推荐答案

有关HTML标记,请使用HTML解析器。

For HTML tags, please use HTML parser.

有关[A] [/ A],你可以像下面

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"

下面是Regex.Replace(我我不是说喜欢,虽然)

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\]",
                            @"<a$1$2>$3</a>", 
                            RegexOptions.Multiline);

这篇关于正则表达式来替换方括号用尖括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆