Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Regex Replacement - C#

RSS
Modified on Thu, Jun 29, 2023, 6:03 AM by Administrator Categorized as Regular Expressions, ·Net Framework

Example

static void Main(string[] args)
{
    var oldValue = "forecolor: rgb ( 200 , 100 , 10 ); backcolor: rgb( 12,13,14);";
    var pattern = @"rgb\s?\(\s?(\d{1,3})\s?\,\s?(\d{1,3})\s?\,\s?(\d{1,3})\s?\)";

    var regex = new Regex(pattern);

    var mc = regex.Matches(oldValue);

    if (!mc.Any())
    {
        Debug.Print("Not found.");
        return;
    }

    var newValue = regex.Replace(oldValue, MatchEvaluatorMethod);

    Debug.Print($"Old: '{oldValue}'");
    Debug.Print($"New: '{newValue}'");
}

private static string MatchEvaluatorMethod(Match item)
{
    var val = item.Groups[0].Value;
    var r = int.Parse(item.Groups[1].Value).ToString("X").PadLeft(2, '0');
    var g = int.Parse(item.Groups[2].Value).ToString("X").PadLeft(2, '0');
    var b = int.Parse(item.Groups[3].Value).ToString("X").PadLeft(2, '0');
    var replaceWith = $"#{r}{g}{b}";
    return replaceWith;
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.