regexcsv

Regex for a CSV matching single fields using an index


I have a simple CSV with numbers:

123,4,563,2334,32,7

I don't find a way to match only the nth position matching the numbers field by field using an index number. Is this solvable with a Regex expression?

The Regex flavour is the one used in the end for the Microsoft Regex.Match Method, but it is only passed as an arugment over a .NET API. I cannot directly program it.

The wanted output is:

  1. 123

  2. 4

  3. 563

  4. 2324

  5. 32

  6. 7

The answer from @C3roe is really a good starting point, but it matches all fields until the correct end of the wanted result. Still the beginning is on position one.

Result of ^(?:\[0-9\]+,){2}(\[0-9\]+) is 123,4,563. The desired result is 563.

So the regular expression works for the first index 0.

Result of ^(?:\[0-9\]+,){0}(\[0-9\]+) is 123. The desired result is 123.

So @Friedrich is also correct with noting the x,y problem. Hopefully I could explain the task better.


Solution

  • You can use a positive lookbehind like this:

    (?<=^(?:\d+,){2})\d+
    

    See the .NET regex demo.

    Customize the {2} to get the number you want.

    Details: