Hendra Anggrian
Hendra Anggrian

Reputation: 5858

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.

Upvotes: 0

Views: 550

Answers (5)

arilupus
arilupus

Reputation: 51

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

Upvotes: 1

L.B
L.B

Reputation: 116108

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

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

Upvotes: 1

Ωmega
Ωmega

Reputation: 43673

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

Upvotes: 2

Moon
Moon

Reputation: 35265

\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.

Upvotes: 0

Rohit Vats
Rohit Vats

Reputation: 81243

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

Upvotes: 0

Related Questions