Ivan Ivan - 28 days ago 8
C# Question

Regular expression to break string into float/alpha parts

I am trying to match

double[M|B]
into double part and alpha part. For example,
47.5B
, or
350M
.

This doesn't work:

var numAlpha = new Regex("(<Numeric>^[0-9]*?:\\.[0-9]*)(<Alpha>[a-zA-Z]+)");
var match = numAlpha.Match("1.65B");

var number = match.Groups["Numeric"].Value;
var alpha = match.Groups["Alpha"].Value;

Answer Source

Your regex contains several issues:

  • Named capturing groups are formed with (?<Name>pattern) syntax
  • A "wild" : symbol is present
  • Your number regex matches a single ., too.

I suggest fixing it the following way (see online demo):

var numAlpha = new Regex(@"(?<Numeric>[0-9]*\.?[0-9]+)(?<Alpha>[a-z]+)", RegexOptions.IgnoreCase);
var match = numAlpha.Match("1.65B");
if (match.Success) 
{
    var number = match.Groups["Numeric"].Value;
    var alpha = match.Groups["Alpha"].Value;
    Console.WriteLine("Number: {0}, Alpha: {1}", number, alpha); // DEMO!
    // => Number: 1.65, Alpha: B
}

Note:

  • If you need to match the whole string, add ^ anchor at the start and $ at the end - @"^(?<Numeric>[0-9]*\.?[0-9]+)(?<Alpha>[a-z]+)$"
  • RegexOptions.IgnoreCase allows using [a-z] instead of [a-zA-Z].