Loading ...

Need to extract last word with regex | CodeAsp.Net

Need to extract last word with regex

Posted in: ASP.NET Topics  »  Web Forms / Data Controls
Subscribe to RSS
  • kevin

    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.

     

     

     
  •   Answered
    raghav_khunger

     

    #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

    <b>[<a href="https://mvp.support.microsoft.com/profile/Raghav">ASP.NET MVP</a>]  [<a href="https://www.microsoftcommunitycontributor.com">Microsoft® Community Contributor</a>] [<a href="http://www.dzone.com/aboutmvb">Dzone MVB</a>] [<a href="https://twitter.com/#!/RaghavKhunger">Follow me on Twitter</a>]</b> <br/><br/><b>[<a href="http://codeasp.net/wiki/view/10/how-to-ask-questions-on-forums">How to ask questions on forums</a>]</b> <br/><br/> "Success does not come to those who wait . . . and it does not wait for anyone to come to it." Anonymous <br/> "Success is simply a matter of luck. Ask any failure." Anonymous
     
  • Page 1 of 1 (2 items)