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");
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With