Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I would like to get the last word in a line.
Some line has a blank at the end and some may not.

I have tried:
XML
\\s[^A-zÀ-ú0-9]+$


But this return the space for the line which end with space.
Posted
Updated 18-May-15 1:19am
v3

I don't know why do you need the regular expression:

C#
string lastWord = input.Split(' ').Last();
 
Share this answer
 
v3
Comments
Maciej Los 18-May-15 7:47am    
5ed!
Leo Chapiro 18-May-15 7:50am    
Thank you, Maciej! :)
Afzaal Ahmad Zeeshan 18-May-15 8:02am    
+5; see keeping something simple is easy! OP should see this post and mark it as solution.
Regex is very powerful but in this case it is like using a sledgehammer to crack a nut. The disadvantage of Regex in this case (as you have discovered) is that there is no equivalent of
StringSplitOptions.RemoveEmptyEntries
although you could use something like
var matches = reg.Split(input).Where(s => !String.IsNullOrEmpty(s));
Personally I prefer the method proposed by _dude_ in Solution 1 but modified to handle empty strings and other anomalies thus:
string lastWord = input.Split(new char[] {' '},
    StringSplitOptions.RemoveEmptyEntries).LastOrDefault();
 
Share this answer
 
Comments
Maciej Los 18-May-15 7:47am    
5ed!
CHill60 18-May-15 7:52am    
Thank you!
Afzaal Ahmad Zeeshan 18-May-15 8:03am    
Good one. +5
you can use the Trim function to remove spaces at the end of the string.
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 18-May-15 8:03am    
How is that an answer to the above problem?
ConnectingKamlesh 18-May-15 8:27am    
because he is already having a regex which is not able handle one situation, i.e. when there is space in the end of the line, so I just proposed a solution which he can apply to his regex without changing his context.
Afzaal Ahmad Zeeshan 18-May-15 8:29am    
Regex can easily do at least something. But this is not a solution. You can write this as a comment.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900