C # regex for number / number / string

I am trying to find patterns {a number} / { a number } / {a string}

. I can get it to number / number

work, but when I add / string

it is not.

An example of what I am trying to find:

15/00969/FUL

      

My regex:

Regex reg = new Regex(@"\d/\d/\w");

      

+3


source to share


4 answers


You have to use +

quantifier , which means 1 or more times

, and it applies to the pattern preceding the quantifier, and I would add a boundary word \b

to match whole words:

\b\d+/\d+/\w+\b

      

C # (using a string string literal so we can just copy / paste regexes from tools or testing services without escaping backslashes):

var rx = new Regex(@"\b\d+/\d+/\w+\b");

      

If you want to accurately determine the number of characters that match some pattern, you can use {}

s:

\b\d{2}/\d{5}/\w{3}\b

      



And finally, if you only have letters in a string, you can use the shorthand class \p{L}

(or \p{Lu}

just uppercase) in C #:

\b\d{2}/\d{5}/\p{L}{3}\b

      

Sample code (also containing capture groups introduced with unescaped (

and )

):

var rx = new Regex(@"\b(\d{2})/(\d{5})/(\p{L}{3})\b");
var res = rx.Matches("15/00969/FUL").OfType<Match>()
                       .Select(p => new
                       {
                           first_number = p.Groups[1].Value,
                           second_number = p.Groups[2].Value,
                           the_string = p.Groups[3].Value
                       }).ToList();

      

Output:

enter image description here

+7


source


Regex reg = new Regex(@"\d+/\d+/\w+");

      

Complete example:



Regex r = new Regex(@"(\d+)/(\d+)/(\w+)");

string input = "15/00969/FUL";
var m = r.Match(input);

if (m.Success)
{
    string a = m.Groups[1].Value;   // 15
    string b = m.Groups[2].Value;   // 00969
    string c = m.Groups[3].Value;   // FUL
}

      

+5


source


You are missing quantifiers in Regex

If you want to match 1 or more items, you must use +

. If you already know the number of items to match, you can specify it using {x}

or {x,y}

for a range ( x

and y

two numbers)

So your regex will become:

Regex reg = new Regex(@"\d/+\d+/\w+");

      

For example, if all the elements you want to match are in this format ( {2 digit}/{5 digit}/{3 letters}

), you can write:

Regex reg = new Regex(@"\d/{2}\d{5}/\w{3}");

      

And it will match 15/00969/FUL

More information on regular expressions can be found here

+3


source


bool match = new Regex(@"[\d]+[/][\d]+[/][\w]+").IsMatch("15/00969/FUL"); //true

      

Regular expression:

[\d]+ //one or more digits
[\w]+ //one or more alphanumeric characters
[/]   // '/'-character

      

+2


source







All Articles