Loading ...

Need to extract last word with regex

Who is online?  0 guests and 0 members
home  »  forums   »  asp.net topics   »  web forms / data controls   » Need to extract last word with regex

Need to extract last word with regex

Posts under the topic: Need to extract last word with regex

Posted: 6/28/2010

Lurker 235  points  Lurker
  • Joined on: 10/16/2009
  • Posts: 47

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.

 

 


tags regex

Posted: 6/28/2010

Guru 16518  points  Guru
  • Joined on: 4/19/2009
  • Posts: 483
  Answered

 

#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


tags c#, regex
Page 1 of 1 (2 items)