Extracts all numbers from the string with regular expression
//------------------------------------------------------------------------------
// Copyright (c) 2003-2009 Whidsoft Corporation. All Rights Reserved.
//------------------------------------------------------------------------------
namespace Whidsoft.WebControls
{
using System;
using System.Drawing;
using System.IO;
using System.Collections;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
/// <summary>
/// Utility class with various useful static functions.
/// </summary>
internal class Util
{
/// <summary>
/// Given a string that contains a number, extracts the substring containing the number.
/// Returns only the first number.
/// Example: "5px" returns "5"
/// </summary>
/// <param name="str">The string containing the number.</param>
/// <returns>The extracted number or String.Empty.</returns>
internal static string ExtractNumberString(string str)
{
string[] strings = ExtractNumberStrings(str);
if (strings.Length > 0)
{
return strings[0];
}
return String.Empty;
}
/// <summary>
/// Extracts all numbers from the string.
/// </summary>
/// <param name="str">The string containing numbers.</param>
/// <returns>An array of the numbers as strings.</returns>
internal static string[] ExtractNumberStrings(string str)
{
if (str == null)
{
return new string[0];
}
// Match the digits
MatchCollection matches = Regex.Matches(str, "(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
// Move to a string array
string[] strings = new string[matches.Count];
int index = 0;
foreach (Match match in matches)
{
if (match.Success)
{
strings[index] = match.Value;
}
else
{
strings[index] = String.Empty;
}
index++;
}
return strings;
}
}
}
Related examples in the same category