![](/img/trans.png)
[英]C# regex: match a string starting with x and ending with y, not including the ending part & match the last occurence of a pattern
[英]Extracting a string starting with x and ending with y
首先,我對此進行了搜索,並且能夠找到如何使用String.Split()之類的東西來根據條件提取字符串。 然而,我無法找到如何根據結束條件提取它。 例如,我有一個文件鏈接到圖像: http://i594.photobucket.com/albums/tt27/34/444.jpghttp://i594.photobucket.com/albums/as/asfd/ghjk6.jpg
: http://i594.photobucket.com/albums/tt27/34/444.jpghttp://i594.photobucket.com/albums/as/asfd/ghjk6.jpg
: http://i594.photobucket.com/albums/tt27/34/444.jpghttp://i594.photobucket.com/albums/as/asfd/ghjk6.jpg
你會注意到所有圖像都以http://
開頭,以.jpg
結尾。 但是,.jpg由http://繼承而沒有空格,這使得這更難一點。
所以基本上我試圖找到一種方法(正則表達式?)從以http://開頭並以.jpg結尾的字符串中提取字符串
正則表達式是最簡單的方法。 如果您不熟悉正則表達式,可以查看Regex Buddy 。 這是一個相對便宜的小工具,我發現在學習時非常有用。 對於您的特定情況,可能的表達式是:
(http://.+?\.jpg)
它可能需要更多的細化,因為有邊界情況可以解決這個問題,但如果文件是一個簡單的列表,它將起作用。
你也可以在這里免費快速測試表達式。
根據您的最新評論,如果您還有其他非圖像的鏈接,那么您需要確保它不是從http://開始一個鏈接並且一直讀到.jpg以獲取下一個圖像。 由於不允許URL有空格,您可以這樣做:
(http://[^\s]+\.jpg)
這基本上說,“匹配以http://開頭並以.jpg結尾的字符串,其中兩者之間至少有一個字符,這些字符都不是空格”。
Regex RegexObj = new Regex("http://.+?\\.jpg");
Match MatchResults = RegexObj.Match(subject);
while (MatchResults.Success) {
//Do something with it
MatchResults = MatchResults.NextMatch();
}
在您的特定情況下,您可以始終按“.jpg”拆分。 您可能最終會在數組末尾添加一個空元素,並且如果需要,必須在每個文件的末尾附加.jpg。 除此之外,我認為它會起作用。
測試了以下代碼,它工作正常:
public void SplitTest()
{
string test = "http://i594.photobucket.com/albums/tt27/34/444.jpghttp://i594.photobucket.com/albums/as/asfd/ghjk6.jpg";
string[] items = test.Split(new string[] { ".jpg" }, StringSplitOptions.RemoveEmptyEntries);
}
它甚至擺脫了空洞的進入......
以下LINQ將通過http:分隔,並確保僅獲取以jpg結尾的值。
var images = from i in imageList.Split(new[] {"http:"},
StringSplitOptions.RemoveEmptyEntries)
where i.EndsWith(".jpg")
select "http:" + i;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.