Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# regex for number/number/string pattern

Tags:

c#

regex

I am trying to find {a number} / { a number } / {a string} patterns. I can get number / number to work, but when I add / string it does not.

Example of what I'm trying to find:

15/00969/FUL

My regex:

Regex reg = new Regex(@"\d/\d/\w");
like image 232
Thomas James Avatar asked Dec 02 '22 14:12

Thomas James


1 Answers

You should use + quantifier that means 1 or more times and it applies to the pattern preceding the quantifier, and I would add word boundaries \b to only match whole words:

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

C# code (using verbatim string literal so that we just could copy/paste regular expressions from testing tools or services without having to escape backslashes):

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

If you want to precise the number of characters corresponding to some pattern, you can use {}s:

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

And, finally, if you have only letters in the string, you can use \p{L} (or \p{Lu} to only capture uppercase letters) shorthand class in C#:

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

Sample code (also featuring capturing 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

like image 109
Wiktor Stribiżew Avatar answered Dec 14 '22 23:12

Wiktor Stribiżew