user3152420
user3152420

Reputation: 27

The regular expression shows me the opposite of what I want in C#

I want to write only numbers in the textbox3 but it shows me the opposite, I mean only letters. When I use @"\D" like a pattern it work. Why?

    public String NingunCaracterEspecial(Control ctrlRegresar)
    {
        String strRegresar = ctrlRegresar.Text;
        String pattern = @"\d";
        String replacement = "";

        return Regex.Replace(strRegresar, pattern, replacement);
    } 

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        textBox3.Text = NingunCaracterEspecial(textBox1);
    }

Upvotes: 0

Views: 186

Answers (2)

O. R. Mapper
O. R. Mapper

Reputation: 20730

As far as I understood from your question:

  • You want to leave all digits intact.
  • You want to remove (replace with an empty string) all letters.

So, the pattern that you indicate is what will be replaced.

If you indicate \d, this will replace all digits, as \d matches a digit. \D is the complement thereof, so if you replace \D, everything that is not a digit (that is, including letters) will get replaced.

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 72991

When I use @"\D" like a pattern it work. Why?

\D is anything that is not a digit.

So you seem to be replacing anything that is not a digit, hence leaving only digits, which is what you want.

Upvotes: 2

Related Questions