Home > database >  How to select each number in a list with RegEx, but only after a specific set of characters?
How to select each number in a list with RegEx, but only after a specific set of characters?

Time:05-20

I have the following RegEx:
/((?<=RGB:\s)\d*){1}[^,\s] /gm
And the following text to use it on:

RGB: 123, 12, 5
HSV: 23, 119, 223
7

I am trying to have it select all 3 numbers that come after "RGB:", but without including "RGB:" or the spaces and commas in the match. I'm fairly new to RegEx and my expression seems to nearly work but I'm stuck on one issue. It only matches the very first number and stops at the comma. I don't understand the cause of this, and I can't get it to work after altering my RegEx many times. My reasoning for doing this is so I can easily replace many of these numbers in a file with new ones with ease. The language I am using is C#.

What I'm trying to do:

RGB: 123, 12, 5
HSV: 23, 119, 223
7
(Match the 3 numbers after "RGB:")

What it is actually doing:

RGB: 123, 12, 5
HSV: 23, 119, 223
7
(It's matching only the first number after "RGB:")

CodePudding user response:

I would match on \bRGB: (\d , \d , \d ), then split the first capture group on comma to get an array of string numbers.

var input = "RGB: 123, 12, 5\nHSV: 23, 119, 223\n7";
var pattern = @"\bRGB: (\d , \d , \d )";
var match = Regex.Match(input, pattern).Groups[1].Value;
var rx = new Regex(@",\s*");
var nums = rx.Split(match);
Array.ForEach(nums, Console.WriteLine);

This prints:

123
12
5

CodePudding user response:

In .NET Regex you can use a variable length lookbehind (demo).

(?<=RGB:[\s\d,]*)\d 

Or an idea to use \G to continue where the previous match ended (demo).

(?<=\G(?!^)|RGB:)[,\s]*(\d )

This one needs a capturing group but is probably overall more efficient.

  • Related