Skip to main content

How To Extract Number from string

In this post i will show how to extract number from string using Regular expression.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExtractNumber.aspx.cs" Inherits="ExtractNumber" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtInput" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnExtract" runat="server" Text="ExtractNumber" OnClick="btnExtract_Click" /><br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ExtractNumber : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnExtract_Click(object sender, EventArgs e)
    {
        lblMessage.Text = ExtractNumbers(txtInput.Text);

    }
    public  string ExtractNumbers(string expr)
    {
        return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]"));
    }
}

Comments

Post a Comment

Popular posts from this blog