簡體   English   中英

正則表達式獲取字符串中最后一個空格后的任何內容

[英]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();

我認為您正在尋找:

[\d-]+$

演示在這里: https : //regex101.com/r/hL9aR8/2

我會使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM