mahi
mahi

Reputation: 27

How to to remove characters from numeric value using regex

I have the value 4,59,999/-. My code is

if (Regex.IsMatch(s,@"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
    string value = Regex.Replace(s, @"[^\d]", " ");
    textBox2.Text= value;
} 

Output is: 4 59 999, I need it to be 459999 (without "," , "/" , "-" and " ").

Upvotes: 2

Views: 89

Answers (8)

Pratyatech Solution
Pratyatech Solution

Reputation: 11

Try something like this it will work 100% in php so just change some syntax for C#

<?php
    $str = "4,59,999/-.";
    echo $str = preg_replace('/[^a-z0-9]/', '', $str);
?>

Upvotes: 0

Claudio P
Claudio P

Reputation: 2203

You are replacing the ",", "/", "-" and " " with a white space. Try this instead:

string value = Regex.Replace(s, @"[^\d]", "");

Hope this helps.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460048

You don't need regex, you could use:

 textBox2.Text = String.Concat(s.Where(Char.IsDigit));

Much better is to use decimal.Parse/TryParse:

string s = "4,59,999/-.";
decimal price;
if (decimal.TryParse(s.Split('/')[0], NumberStyles.Currency, NumberFormatInfo.InvariantInfo, out price))
    textBox2.Text = price.ToString("G");

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Linq is a possible solution:

  String s = "4,59,999/-";
  ...
  textBox2.Text = new String(s.Where(item => item >= '0' && item <= '9').ToArray());

Upvotes: 0

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98740

How about without regex?

var s = "4,59,999/-";
var array = s.Where(c => char.IsDigit(c)).ToArray(); 

or shorter

var array = s.Where(char.IsDigit).ToArray(); 

enter image description here

And you can use this array in a string(Char[]) constructor.

var result = new string(array); // 459999

Upvotes: 3

PiranhaGeorge
PiranhaGeorge

Reputation: 999

Currently you're replacing these characters with a space. Use an empty set of quotes instead.

if (Regex.IsMatch(s,@"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
    string value = Regex.Replace(s, @"[^\d]", "");
    textBox2.Text= value;
} 

Upvotes: 1

Jo&#227;o Vargas
Jo&#227;o Vargas

Reputation: 21

Should just be a case of replacing it with an empty string instead of a space?

Regex.Replace(s, @"[^\d]", String.Empty);

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

Just replace with empty string.

string value = Regex.Replace(s, @"[^\d]", ""); // See the change in the replace string.
textBox2.Text= value;

Note You don't require the if as the regex replace will work only if there is a match for non digits ([^\d])

Upvotes: 1

Related Questions