Reputation: 381
I have a regex
Regex.Match(result, @"\b(?<=Pay Rate)(\D*)(\d+(?:\.\d+)?)");
This works great but it only works when there's only 1 rate. It only grabs the first one, which is great because when the Pay Rate only has 1 rate this perfectly works. However, there's a possibility that the Pay Rate can have multiple rates. For example,
Pay Rate: 12.12% 13.13% 14.14% 15.15% (I don't know, it can go on and on and on). So when there is more than 1 rate, I want to just get the highest rate (always 2 decimal places). And when there's only one, just print the first one.
Upvotes: 0
Views: 283
Reputation: 16079
You can use Max()
from Linq,
var input = "12.12% 13.13% 14.14% 15.15% 10.10%";
var result = input.Replace("%","") //Remove all % from input string in one go
.Split(" ") //Split by space
.Select(decimal.Parse) //Convert IEnumerable of string to IEnumerable of float
.Max(); //Get Max element from given list
Upvotes: 0
Reputation: 19651
You may use repeated capturing groups for this, parse the number found in each group capture, and then get the max rate. Because we'll be using a capturing group anyway, I would drop the Lookarounds. Something like this should work:
string input = "Pay Rate: 12.12% 13.13% 14.14% 15.15%";
var match = Regex.Match(input, @"\bPay Rate:(?:\s*(\d+(?:\.\d+)?)%)+");
if (match.Success)
{
var rate = match.Groups[1]
.Captures.OfType<Capture>()
.Select(c => decimal.Parse(c.Value))
.Max();
Console.WriteLine(rate); // 15.15
}
If you're certain that the max rate is always the last one, you could simply use:
Regex.Match(input, @"\bPay Rate:(?:\s*(\d+(?:\.\d+)?)%)+").Groups[1].Value
Upvotes: 1
Reputation: 2490
You can achieve by using lambda expressions
var payRate = "12.12% 13.13% 14.14% 15.15% 10.10%";
var splitPayRate = payRate.Split(new char[] {' '});
var maxPayRate = splitPayRate.Select(x => Convert.ToDecimal(x.Replace("%",""))).ToList().OrderByDescending(x=>x).Take(1).FirstOrDefault();
Upvotes: 1