2

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 " ").

1
  • I suspect a design flaw. Why is that value a string in the first place? Commented Jun 18, 2015 at 9:28

8 Answers 8

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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");

Comments

1

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])

Comments

1

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

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

Comments

1

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;
} 

Comments

1

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

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

Hope this helps.

3 Comments

"" is not whitespace. It is the empty string.
@phoog Yes but I tries to explain what the OP dix wrong and not what he should do
Ah, I see. I have edited your answer slightly to make it clearer.
0

Linq is a possible solution:

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

Comments

0

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);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.