I want to write a regexp to get multiple matches of the first character and next three digits. Some valid examples: A123, V322, R333. I try something like that
[a-aA-Z](1)\d3
but it gets me just the first match! Could you possibly show me, how to rewrite this regexp to get multiple results?Thank you so much and Have a nice day!
Your regex does not work because it matches:
[a-aA-Z]
- an ASCII letter, then(1)
- a 1
digit (and puts into a capture)\d
- any 1 digit3
- a 3
digit.So, it matches Y193
, E103
, etc., even in longer phrases, where Y
and E
are not first letters.
You need to use a word boundary and fix your pattern as
\b[a-aA-Z][0-9]{3}
NOTE: if you need to match it as a whole word, add \b
at the end: \b[a-aA-Z][0-9]{3}\b
.
See the regex demo.
Details:
\b
- leading word boundary[a-aA-Z]
- an ASCII letter[0-9]{3}
- 3 digits.C# code:
var results = Regex.Matches(s, @"\b[a-aA-Z][0-9]{3}")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
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