Reputation: 27
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
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
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
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
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
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();
And you can use this array in a string(Char[])
constructor.
var result = new string(array); // 459999
Upvotes: 3
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
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
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