[英]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? 之前的“ 如何检查字符串中是否包含从a到z的字母? I have learnt how to use Regex to detect letters from a
to z
. 我已经学习了如何使用Regex来检测从a
到z
字母。
Can we make Regex to detect any symbols too? 我们可以使Regex也检测到任何符号吗? Like . , ! ? @ # $ % ^ & * ( )
喜欢. , ! ? @ # $ % ^ & * ( )
. , ! ? @ # $ % ^ & * ( )
. , ! ? @ # $ % ^ & * ( )
or any other else. . , ! ? @ # $ % ^ & * ( )
或其他任何符号。
More specifically, I want to accept only digits in my string
. 更具体地说,我只想接受string
数字 。
To match string containing only digits or empty string use regex pattern ^\\d*$
要匹配仅包含数字的字符串或空字符串,请使用正则表达式模式^\\d*$
To match string containing only digits, not allowing an empty string use regex pattern ^\\d+$
要匹配仅包含数字的字符串,不允许使用空字符串,请使用正则表达式模式^\\d+$
Console.WriteLine((new Regex(@"^\d+$")).IsMatch(string) ? "Yes" : "No");
Test this code here . 在此处测试此代码。
Learn more at http://www.regular-expressions.info/dotnet.html 在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. 您可以通过遵循某些约定来创建自己的Regex
。 Refer to this Regex Cheat Sheet to create your own Regex. 请参考此Regex备忘单以创建自己的Regex。
\\d+
will match 1 or more digits. \\d+
将匹配1个或多个数字。
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. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.