当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to replace these strings via regex?

问题描述:

I work on a project target on Windows Phone 7.5 and above.

What I Want

make strA to strB,

strA has bunch of [img]attachmenti[/img] pair, and I want convert the [img] pair to another pair which I can use it in a RichTextBox.[I have an array which holds the image's url and I will pass it to the Image Source property]

//example data

strA = this a good day.[img]attachment1[/img]I love it[img]attachment2[/img];

strB = this a good day.<InlineUIContainer><Image Source="XXXXXX"></Image><InlineUIContainer>I love it<InlineUIContainer><Image Source="XXXXXX"></Image><InlineUIContainer>


What's the problem

I use MatchCollection to get all the match corresponding parts in the string. I check the result in the immediate window, the code is OK, but the problem is MatchCollection is readonly, I can not replace its value, so how can I replace these strings after matching or is there a better way to implement this?

 foreach (var item in rawdata.data)

{

if ( item.thumbnail != null)

{

MatchCollection mc = Regex.Matches(item.text, @"\[img\](.+?)\[/img\]", RegexOptions.Compiled | RegexOptions.Singleline);

int i = 0;

foreach (Match nextMatch in mc)

{

string imghead = @"<InlineUIContainer><Image" + " Source=\"" + item.thumbnail[i] + "\">";

StringBuilder sb = new StringBuilder();

sb.Append(@"<InlineUIContainer><Image");

sb.Append(" Source=\"");

sb.Append(item.thumbnail[i]);

sb.Append("\">");

sb.Append(@"</Image></InlineUIContainer>");

nextMatch.Value.Replace( nextMatch.Value, sb.ToString());

i = i + 1;

}

}

}

网友答案:
string str = Regex.Replace(item.text, @"\[img\](.+?)\[/img\]", @"<InlineUIContainer><Image Srouce=\"$1\" /></InlineUIContainer>", RegexOptions.IgnoreCase);
分享给朋友:
您可能感兴趣的文章:
随机阅读: