简体   繁体   中英

How to ignore specific characters in TextBox?

I would like to know how can I ignore some characters when type in a TextBox . I have this textbox which is working with AutoCompleteCustomSource , when I'm looking for a product I would like to type for example 5 * my product and ignore the part 5 * in that moment to find the product as it should be, because if I don't ignore 5 * it will not find any product because I have no one including numbers or that symbol.

What 5 * (could be any number not just 5) is suppose to do is to add to a DataGridView that product 5 times in this example, I tried with a regex to find a matches when some combination like this is done

Regex rx = new Regex(@"^[0-9*\s]+$");
  
string text = txtBuscadorProducto.Text;

//Find matches
MatchCollection matches = rx.Matches(text);

MessageBox.Show(matches.Count.ToString());

but I have no idea how to make to ignore those characters without delete them from the TextBox , any ideas or another way to achieve this would be nice, hope you can help me, thanks.

You could omit the $ which asserts the end of the string. Instead of using Matches, you could use Replace and then replace that match with an empty string.

For example:

Regex rx = new Regex(@"^[0-9*\s]+");
Console.WriteLine(rx.Replace("5 * my product", "")); //my product

C# demo

Using a character class is kind of a broad match because is can also only match digits or whitespace characters. A more exact match for your format would be:

^\d+\s\*\s
  • ^ Assert start of the string
  • \d+ Match 1+ digits
  • \s+\*\s+ Match 1+ whitespace chars, * and 1+ whitespace chars

Regex demo

For example

Regex rx = new Regex(@"^\d+\s\*\s");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM