[英]Regex to get anything after last space in a string
我有一個字符串,里面有一堆單詞,我想要的只是最后一個單詞。 什么是正則表達式?
例如:
This is some sample words to work with
我只是想with
從上面的字符串。
一個更簡單的解決方案是使用Split
方法:
string text = "This is some sample text to work with";
string last = text.Split(' ').Last();
我會使用LastIndexOf
,應該表現更好。
string text = "This is some sample words to work with";
string last = text.Substring(text.LastIndexOf(' '));
當然,如果文本有可能沒有任何空格,您必須確保您沒有嘗試從 -1 索引中提取子字符串。
我猜你的需要雖然有點晚了,但這應該有效:
將 "[a-zA-Z]+$" 替換為 "[\\S]+$" => 將采用所有非空格字符。
如果您堅持使用正則表達式,那么以下內容將對您有所幫助
/[a-zA-Z]+$/
例子
Match m = Regex.Matches("This is some sample words to work with", "[a-zA-Z]+$")[0];
Console.WriteLine(m.Value);
=> with
根據原始問題(最后沒有數字)獲得“with”:
[^\W]+$
Regex.Match("This is some sample words to work with", @"[^\W]+$").Value == "with"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.