Reputation: 5858
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
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
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
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
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
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