Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# extract words using regex

Tags:

c#

regex

parsing

I've found a lot of examples of how to check something using regex, or how to split text using regular expressions.

But how can I extract words out of a string ?

Example:

aaaa 12312 <asdad> 12334 </asdad>

Lets say I have something like this, and I want to extract all the numbers [0-9]* and put them in a list.

Or if I have 2 different kind of elements:

aaaa 1234 ...... 1234 ::::: asgsgd

And I want to choose digits that come after ..... and words that come after ::::::

Can I extract these strings in a single regex ?

like image 711
Yochai Timmer Avatar asked Dec 06 '25 16:12

Yochai Timmer


2 Answers

Here's a solution for your first problem:

   class Program
    {
        static void Main(string[] args)
        {
            string data = "aaaa 12312 <asdad> 12334 </asdad>";

            Regex reg = new Regex("[0-9]+");

            foreach (var match in reg.Matches(data))
            {
                Console.WriteLine(match);
            }

            Console.ReadLine();
        }
    }
like image 121
JoshBerke Avatar answered Dec 08 '25 08:12

JoshBerke


In the general case, you can do this using capturing parentheses:

string input = "aaaa 1234 ...... 1234 ::::: asgsgd";
string regex = @"\.\.\.\. (\d+) ::::: (\w+)";
Match m = Regex.Match(input, regex);

if (m.Success) {
    int numberAfterDots = int.Parse(m.Groups[1].Value);
    string wordAfterColons = m.Groups[2].Value;
    // ... Do something with these values
}

But the first part you asked (extract all the numbers) is a bit easier:

string input = "aaaa 1234 ...... 1234 ::::: asgsgd";
var numbers = Regex.Matches(input, @"\d+")
                   .Cast<Match>()
                   .Select(m => int.Parse(m.Value))
                   .ToList();

Now numbers will be a list of integers.

like image 45
Timwi Avatar answered Dec 08 '25 07:12

Timwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!