繁体   English   中英

C#-使Regex检测到任何非数字字符

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

之前的“ 如何检查字符串中是否包含从a到z的字母? 我已经学习了如何使用Regex来检测从az字母。

我们可以使Regex也检测到任何符号吗? 喜欢. , ! ? @ # $ % ^ & * ( ) . , ! ? @ # $ % ^ & * ( ) . , ! ? @ # $ % ^ & * ( )或其他任何符号。

更具体地说,我只想接受string 数字

要匹配仅包含数字的字符串或空字符串,请使用正则表达式模式^\\d*$

要匹配仅包含数字的字符串,不允许使用空字符串,请使用正则表达式模式^\\d+$

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

在此处测试此代码。


http://www.regular-expressions.info/dotnet.html上了解更多信息

using System.Text.RegularExpressions;

首先创建正则表达式编号

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

并确保这是数字

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

如果您想要一个比正则表达式更快更易于维护的解决方案:

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

您可以通过遵循某些约定来创建自己的Regex 请参考此Regex备忘单以创建自己的Regex。

\\d+将匹配1个或多个数字。

例如:

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

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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