C # regex for number / number / string
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:
source to share
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
}
source to share
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
source to share