E-A
E-A

Reputation: 2025

How to do this Regex in C#?

I've been trying to do this for quite some time but for some reason never got it right.

There will be texts like these:

The rule is there will be EXACTLY 5 digit number (no more or less) after that a 1 SPACE (or no space at all) and some text after as shown above. I would like to have a MATCH using a regex pattern and extract THE NUMBER and SPACE and THE TEXT.

Is this possible? Thank you very much!

Upvotes: 0

Views: 108

Answers (4)

Andras Zoltan
Andras Zoltan

Reputation: 42363

Since from your wording you seem to need to be able to get each component part of the input text on a successful match, then here's one that'll give you named groups number, space and text so you can get them easily if the regex matches:

(?<number>\d{5})(?<space>\s?)(?<text>\w+)

On the returned Match, if Success==true then you can do:

string number = match.Groups["number"].Value;
string text = match.Groups["text"].Value;
bool hadSpace = match.Groups["space"] != null;

Upvotes: 2

Priyank Patel
Priyank Patel

Reputation: 7006

string test = "12345 SOMETEXT";
string[] result = Regex.Split(test, @"(\d{5})\s*(\w+)");

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

You could use the Split method:

public class Program
{
    static void Main()
    {
        var values = new[] 
        { 
            "12325 NHGKF", 
            "34523 KGJ", 
            "29302 MMKSEIE", 
            "49504EFDF" 
        };
        foreach (var value in values)
        {
            var tokens = Regex.Split(value, @"(\d{5})\s*(\w+)");
            Console.WriteLine("key: {0}, value: {1}", tokens[1], tokens[2]);
        }
    }
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

The expression is relatively simple:

^([0-9]{5}) ?([A-Z]+)$

That is, 5 digits, an optional space, and one or more upper-case letter. The anchors at both ends ensure that the entire input is matched.

The parentheses around the digits pattern and the letters pattern designate capturing groups one and two. Access them to get the number and the word.

Upvotes: 1

Related Questions