字符串处理,提取和从字符串
我有可能包含一个或多个图像标签字符串中删除图像标记...字符串处理,提取和从字符串
我已经写了一个片断从字符串 滤除图像标签,如
string test = "Hello there <img>Image1</img> How are you ?<img>Image2</img>";
int imgstartindex = test.IndexOf("<img>");
int imgendindex = test.IndexOf("</img>");
List<string> imagetags = new List<string>();
while(imgstartindex!=-1 && imgendindex!=-1)
{
string imagetag = test.Substring(imgstartindex, (imgendindex + 6)-imgstartindex);
imagetags.Add(imagetag);
test= test.Replace(imagetag, "");
imgstartindex = test.IndexOf("<img>");
imgendindex = test.IndexOf("</img>");
}
输出:
test="Hello there How are you?"
imagetags:
"<img>Image1</img>" [0]
"<img>Image2</img>" [1]
有更好的选择吗?
您可以使用此正则表达式,这为您完成所有:
<img>(.*?)<\/img>
它的图像标签,然后在任何非贪婪匹配,其次是图像结束标签相匹配。
使用方法如下:
string s = Regex.Replace(@"abc<img>def</img>ghi", @"<img>(.*?)<\/img>", "$1");
(第一个参数是你的输入)
我不想丢失图片标签,Patrick 。我也需要这些。 –
你为什么不这么说?不用担心,你可以使用['Regex.Match'](https://msdn.microsoft.com/en-us/library/system.text.regularexpressions .regex.matches%28v = vs.110%29.aspx)来获得匹配并替换它们,然后你必须手工完成更多的处理。 –
这是有效的,但不要认为这通常是一种好方法解析标签数据如xml或html:http://blog.codinghorror.com/pa rsing-html-the-cthulhu-way/ – weston
我想这是不是真的HTML吗? –
Ehhh,在给出答案后不要改变你的问题。这使得其他读者不在。我试图在评论中给出最新的答案。 –
对不起:(忘了添加我需要的输出 –