Reputation: 5841
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.
Upvotes: 2
Views: 16121
Reputation: 1133
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"
Upvotes: 1
Reputation: 21
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.
Upvotes: 2
Reputation: 8792
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();
Upvotes: 5
Reputation: 11116
I think you are looking for :
[\d-]+$
demo here: https://regex101.com/r/hL9aR8/2
Upvotes: 6
Reputation: 26687
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
Upvotes: 1
Reputation: 5442
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.
Upvotes: 2