I have a string that has a bunch of words in it and all I want is the last word. What would be the Regex for this?
For example:
This is some sample words to work with
I would just want with
from the above string.
A far easier solution would be to do it with the Split
method:
string text = "This is some sample text to work with";
string last = text.Split(' ').Last();
I would use LastIndexOf
, should perform better.
string text = "This is some sample words to work with";
string last = text.Substring(text.LastIndexOf(' '));
Of course if there's a chance that the text won't have any whitespace, you would have to make sure you are not trying to substring from -1 index.
Altough a bit late for your need I guess, but this should work:
Replace "[a-zA-Z]+$" with "[\\S]+$" => will take all characters that are not spaces.
If you insist on using regex, then following will help you
/[a-zA-Z]+$/
Example
Match m = Regex.Matches("This is some sample words to work with", "[a-zA-Z]+$")[0];
Console.WriteLine(m.Value);
=> with
Per original question (without the numbers at the end) to get "with":
[^\W]+$
Regex.Match("This is some sample words to work with", @"[^\W]+$").Value == "with"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.