【发布时间】:2013-05-29 18:38:43
【问题描述】:
我有什么
string ImageRegPattern = @"http://[\w\.\/]*\.jpg|http://[\w\.\/]*\.png|http://[\w\.\/]*\.gif";
string a ="http://www.dsa.com/asd/jpg/good.jpgThis is a good dayhttp://www.a.com/b.pngWe are the Best friendshttp://www.c.com";
我想要什么
string[] s;
s[0] = "http://www.dsa.com/asd/jpg/good.jpg";
s[1] = "This is a good day";
s[2] = "http://www.a.com/b.png";
s[3] = "We are the Best friendshttp://www.c.com";
邦斯:
如果 url 可以像下面那样拆分,那会更好,但如果不是,那也没关系。
s[3] = "We are the Best friends";
s[4] = "http://www.c.com";
问题是什么
我尝试使用下面的代码来拆分字符串,
string[] s= Regex.Split(sourceString, ImageRegPattern, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
但结果并不好,Split 方法似乎取出了所有匹配 ImageRegPattern 的字符串。但我希望他们留下来。我检查了 MSDN 上的 RegEx 页面,似乎没有合适的方法来满足我的需要。那么该怎么做呢?
【问题讨论】:
-
我不认为有任何通用的解决方案来拆分该字符串(当然你可以制定一些方法来做到这一点,但它会非常具体)。你从 RegEx 中得不到任何回报,因为它在比赛中分裂。我个人会更改字符串的格式,除非有充分的理由不让您在字符串中添加分隔符。
-
给定一个逗号分隔的列表,
Regex.Split("1,2,3", ",")将返回数组["1","2","3"]。您提供的模式定义了分隔符,而不是您想要保留的内容。Regex.Split不是你想在这里使用的。您试图保留文本 和 分隔符,这不是Split所做的。
标签: c# regex arrays string split