Search code examples
regexpcrebbedit

How to match a particular number/field in CSV file consisting of only numbers separated by commas using regex?


I am using BBEdit 12.6 to highlight certain numbers in different colors; to improve readability, in this regard,

Kindly help with a regex expression that would match no. 80 / 42 / 55 (8th field) in below sample file.

    10,20,30,40,50,60,70,80,90,100

    12,22,32,42,52,62,72,42,85,102

    15,25,35,45,55,65,75,55,65,105

As these are all numbers, I have used regex expressions to match the third number from end of line. but, its matching all three last number fields, not just one. this is not a search/replace operation, instead this pattern will be used in .plist file for color coding files using CLM https://www.barebones.com/support/develop/clm.html

the expression I have used, but problem is, it matches the final 3 number fields, not just one.

(?x:(\d+,\d+)(?:,\d+$))

a correct regex expression should match just the 8th field.


Solution

  • You may match 1+ digits that are followed with two occurrences of a comma and 1+ digits at the end of the line/string:

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

    See the regex demo and the regex graph:

    enter image description here

    Details

    • \d+ - 1+ digits
    • (?=(?:,\d+){2}$) - a positive lookahead ((?=...)) that matches a location immediately followed with two occurrences ((?:...){2}) of , and 1+ digits (,\d+) at the end of the string ($).