2

I'm missing something obvious. I want to use a pattern like "\d{7}", and, for an input of "12345678", get matches of "1234567" and "2345678".

It's gotta be easy, right?

C# or VB.Net. Thanks!

Per suggestions, I tried the following code, to no avail (g.ToString is blank each time):

Dim r As New System.Text.RegularExpressions.Regex("(?=\d{7})")
Dim m As MatchCollection = r.Matches("12345678")
For each g As match In m
    Console.WriteLine(String.Format("Match is {0}", g.ToString))
Next
Ivan Pelly
  • 147
  • 2
  • 12
  • 1
    Use `Regex.Matches()` which returns a `MatchCollection` with `Group` objects. You can then iterate the `MatchCollection`. The first `Group` on each `Match` will be the full match, with subsequent `Group` objects being any sub-captures. See here: https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.matches?view=netframework-4.7.2 – Charleh Mar 05 '19 at 15:08
  • See [this answer](https://stackoverflow.com/a/41989091/3832970). – Wiktor Stribiżew Mar 05 '19 at 15:09
  • 2
    @Charleh, that will not work, as Regex.Matches() on its own will not produce overlapping matches... –  Mar 05 '19 at 15:13
  • Another duplicate question that might be helpful: https://stackoverflow.com/questions/320448/overlapping-matches-in-regex –  Mar 05 '19 at 15:16
  • @elgonzo yeah missed that part of the q, thought it was just "how to use Regex to get multiple matches" rather than "how to match multiple times in the same string" – Charleh Mar 05 '19 at 16:53
  • But to be fair, the regex used is already attempting to do this - it's just not right :) – Charleh Mar 05 '19 at 16:55
  • So the issue is probably that you are already matching 3 times but you are using a non-capturing assertion - try something like `(?=(\d{7}))` which will place the capture in subgroup 1 for example – Charleh Mar 05 '19 at 16:58
  • @Charleh I updated my sample code with the suggestion (?=(\d{7})) but the outcome is the same. Matchcollection "m" has two matches, but they both report blank when `g.ToString` is called. – Ivan Pelly Mar 05 '19 at 19:12
  • Yes, because the matches themselves will be blank but the second group in each match (group 1) will be the subcapture which will hold the value. `Match.ToString` will always give you group 0 which for a noncapturing lookahead will not match anything and will return a blank. – Charleh Mar 06 '19 at 10:21
  • Try it here: http://regexstorm.net/tester - I can clearly see it working (look at the `Table` tab after putting my suggested regex tweak/your numerical string in) - e.g. http://regexstorm.net/tester?p=%28%3f%3d%28%5cd%7b7%7d%29%29&i=12345678 – Charleh Mar 06 '19 at 10:22
  • @Charleh nailed it! The observation about the subcapture is the part I was missing. Thank you * 10^6 – Ivan Pelly Mar 06 '19 at 14:36
  • No problem, + the 10^6 made me laugh! – Charleh Mar 06 '19 at 16:05

0 Answers0