Get Specific Pattern From string C#

Hemanth B 886 Reputation points

This is a different question. I have searched the web but couldn't find any solution.
For example I have this string: 9% of 89.
Now the user may type in any number instead of 9 and 89.
Like for example, 3% of 45.
How do I get the pattern from the string and extract those numbers?
Example: "x% of y".

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,392 questions
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 26,166 Reputation points

    This sounds like a user input design question. I would use two inputs; one for the percent and one for the integer. This is much easier to validate then a string.

    If you really need to parse the string then replace the "%" with an empty string, split the string by the "of", then use int.TryParse() to convert the string to an integer.

    String.Replace Method
    String.Split Method

    The following code assumes you provided an accurate use case.

    string input = "3% of 45".ToUpper();;  
    input = input.Replace("%", "");  
    string[] values = input.Split("OF", StringSplitOptions.TrimEntries);  
    int per = 0;  
    int total = 0;  
    int.TryParse(values[0], out per);  
    int.TryParse(values[1], out total);  
    Console.WriteLine($"{(decimal)per / 100.00m}");  



  2. Michael Taylor 49,251 Reputation points

    If you're looking to parse the string in a fixed format (such as from a data file) then regular expressions are the most common approach provided the pattern is relatively straightforward. The Regex class is designed for this. There are quite a few Regex testers floating around online for you to test with. Personally I used the Regex Editor Lite VS extension but you can use anything to verify your expression.

    You need to capture 2 sets of values, the value and the percentage therein so you have to use capture groups.

       var re = new Regex(@"^(?<percent>\d+)%\s+of\s+(?<value>\d+)$", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);  
       var match = re.Match(input);  
       if (match.Success)  
           //Since using regex here we'll assume the values are good but could still fail with large integers  
           var percentage = Int32.Parse(match.Groups["percent"].Value);  
           var value = Int32.Parse(match.Groups["value"].Value);  

    If you need to do this only once then you can simplify the code to using the Regex.Match static method instead but if you need it more than once then create a static instance instead for perf reasons.