Click here to Skip to main content
15,851,387 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to filter a string like this it may contain characters symbols etc

Amount 10.05 $

and i need an output like this contains a float value ( after eliminating the string and symbols except "." )

10.05

i tried the below code but it eliminate the decimal part also


<pre lang="c#">

key="!$%^ amount 10.05$";

  Regex.Replace(key, @"\D", "");



but it returns 10055
Posted

Use this

C#
//Convert the string to decimal or interger
       public static decimal GetNumbersfromstring(string param)
       {
           //for decimal
           string deci = string.Join(null, System.Text.RegularExpressions.Regex.Split(param, "[^.\\d]"));

           //for integer
           string inte = string.Join(null, System.Text.RegularExpressions.Regex.Split(param, "[^\\d]"));

           return Convert.ToDecimal(deci);
       }



Main program

C#
Console.WriteLine(GetNumbersfromstring("Amount 10.05 $"));


Output

10.05

If you find useful rate it.
 
Share this answer
 
v2
Use:
C#
string result = Regex.Replace(key, @"[^\d\.]", "");
 
Share this answer
 
Comments
vishnulalr 31-Aug-12 2:34am    
great it works thanks Zoltán Zörgő
Zoltán Zörgő 31-Aug-12 2:36am    
You are welcome!
Hi vishnulalr,

Try using pattern I've demonstrated below:


C#
key="!$%^ amount 10.05$";

  Regex.Replace(key, @"[a-zA-Z $]","");


This will return you what you expected it to.

Hope this helps.

Happy Coding!
-Sunny.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900