简体   繁体   中英

C# - make Regex detects any character that isn't digit

Previously on How to check if a String contains any letter from a to z? I have learnt how to use Regex to detect letters from a to z .

Can we make Regex to detect any symbols too? Like . , ! ? @ # $ % ^ & * ( ) . , ! ? @ # $ % ^ & * ( ) . , ! ? @ # $ % ^ & * ( ) or any other else.

More specifically, I want to accept only digits in my string .

To match string containing only digits or empty string use regex pattern ^\\d*$

To match string containing only digits, not allowing an empty string use regex pattern ^\\d+$

Console.WriteLine((new Regex(@"^\d+$")).IsMatch(string) ? "Yes" : "No");

Test this code here .


Learn more at http://www.regular-expressions.info/dotnet.html

using System.Text.RegularExpressions;

create regex number first

private Boolean number(string obj)
        {
            Regex r = new Regex(@"^[0-9]+$");
            Match m = r.Match(obj);
            if (m.Success == true) return true;
            else { return false; }
        }

and make sure that is number

if (number(textBox1.Text) == true)
            {
                MessageBox.Show("text box couldn't filled with numbers", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

If you want a faster-than-regex and easier-to-maintain solution :

string num = "123456a";
bool isOnlyDigits = num.All(char.IsDigit);

You can create your own Regex by just following certain conventions. Refer to this Regex Cheat Sheet to create your own Regex.

\\d+ will match 1 or more digits.

For example:

var myString = @"fasd df @###4 dfdfkl  445jlkm  kkfd ## jdjfn ((3443  ";
var regex = new Regex(@"(\d+)");
var matches = regex.Match(myString); // This will match: 4, 445 and 3443

Hope this helps.

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