Kai Kai - 1 month ago 6
C# Question

Regex to extract digits followed by specific word

Using Regex, I want to extract digits which are followed by a specific word.


The number of digits is not finite.



Sample input:

My address is 1234@abc.com and you can send SMS to me.


Expected Result.

1234


In this case, the specific word is
@abc.com
, and the digits followed by this word need to be extracted.

Answer

Use the regular expression groups : on MSDN.

In C#, try this :

string pattern = @"(\d+)@abc\.com";
string input = "My address is 15464684@abc.com and you can send SMS to me";
Match match = Regex.Match(input, pattern);

// Get the first named group.
Group group1 = match.Groups[1];
Console.WriteLine("Group 1 value: {0}", group1.Success ? group1.Value : "Empty");