Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp multiply matches in text

Tags:

c#

regex

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! enter image description here Could you possibly show me, how to rewrite this regexp to get multiple results?Thank you so much and Have a nice day!

like image 305
Qwerty Qwerty Avatar asked May 12 '17 16:05

Qwerty Qwerty


1 Answers

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 digit
  • 3 - 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();
like image 193
Wiktor Stribiżew Avatar answered Sep 28 '22 00:09

Wiktor Stribiżew