Choose a location:
Hi Experts,
I have a long text I need to extract the last word of that text with regex. Say this is my text "This is ....... my text text". Now I want to extract the "text" word out of it. Please help me.
#region Using Directives using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Collections; using System.Text.RegularExpressions; using System.Threading; #endregion public class Example { public static void Main() { const string pattern = "[^ ]*$"; var regex = new Regex(pattern); var match=regex.Match("This is ....... my text"); Console.WriteLine(match.Value); Console.ReadLine();//Output: text } }
Explanation of regex:
[^ ]*$
Match any character that is NOT a “ ” «[^ ]*»
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Assert position at the end of the string (or before the line break at the end of the string, if any) «$»
Created with RegexBuddy