scapegoat17
scapegoat17

Reputation: 5841

Regex to get anything after last space in a string

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

Answers (6)

mhapps
mhapps

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

Jacques
Jacques

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

PiotrWolkowski
PiotrWolkowski

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

aelor
aelor

Reputation: 11116

I think you are looking for :

[\d-]+$

demo here: https://regex101.com/r/hL9aR8/2

Upvotes: 6

nu11p01n73R
nu11p01n73R

Reputation: 26687

If you insist on using regex, then following will help you

/[a-zA-Z]+$/

Regex Demo

Example

Match m = Regex.Matches("This is some sample words to work with", "[a-zA-Z]+$")[0];
Console.WriteLine(m.Value);
=> with

Upvotes: 1

Moti Azu
Moti Azu

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

Related Questions