C# 如何验证字符串以仅允许其中包含字母数字字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1046740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:56:06  来源:igfitidea点击:

How can I validate a string to only allow alphanumeric characters in it?

c#regex

提问by mrblah

How can I validate a string using Regular Expressions to only allow alphanumeric characters in it?

如何使用正则表达式验证字符串以仅允许其中包含字母数字字符?

(I don't want to allow for any spaces either).

(我也不想允许有任何空格)。

采纳答案by cletus

Use the following expression:

使用以下表达式:

^[a-zA-Z0-9]*$

ie:

IE:

using System.Text.RegularExpressions;

Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
  ...
}

回答by Peter Boughton

^\w+$will allow a-zA-Z0-9_

^\w+$将会允许 a-zA-Z0-9_

Use ^[a-zA-Z0-9]+$to disallow underscore.

使用^[a-zA-Z0-9]+$不允许下划线。

Note that both of these require the string not to be empty. Using *instead of +allows empty strings.

请注意,这两个都要求字符串不能为空。使用*代替+允许空字符串。

回答by JP Alioto

You could do it easily with an extension function rather than a regex ...

您可以使用扩展函数而不是正则表达式轻松完成...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    for (int i = 0; i < str.Length; i++)
    {
        if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
            return false;
    }

    return true;
}

Per comment :) ...

每条评论:) ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}

回答by kyoryu

While I think the regex-based solution is probably the way I'd go, I'd be tempted to encapsulate this in a type.

虽然我认为基于正则表达式的解决方案可能是我要走的路,但我很想将其封装在一种类型中。

public class AlphaNumericString
{
    public AlphaNumericString(string s)
    {
        Regex r = new Regex("^[a-zA-Z0-9]*$");
        if (r.IsMatch(s))
        {
            value = s;                
        }
        else
        {
            throw new ArgumentException("Only alphanumeric characters may be used");
        }
    }

    private string value;
    static public implicit operator string(AlphaNumericString s)
    {
        return s.value;
    }
}

Now, when you need a validated string, you can have the method signature require an AlphaNumericString, and know that if you get one, it is valid (apart from nulls). If someone attempts to pass in a non-validated string, it will generate a compiler error.

现在,当你需要一个经过验证的字符串时,你可以让方法签名需要一个 AlphaNumericString,并且知道如果你得到一个,它是有效的(除了空值)。如果有人试图传入未经验证的字符串,则会生成编译器错误。

You can get fancier and implement all of the equality operators, or an explicit cast to AlphaNumericString from plain ol' string, if you care.

如果您关心的话,您可以更高级并实现所有相等运算符,或者从普通 ol' 字符串显式转换为 AlphaNumericString。

回答by jgauffin

In .NET 4.0 you can use LINQ:

在 .NET 4.0 中,您可以使用 LINQ:

if (yourText.All(char.IsLetterOrDigit))
{
    //just letters and digits.
}

yourText.Allwill stop execute and return falsethe first time char.IsLetterOrDigitreports falsesince the contract of Allcannot be fulfilled then.

yourText.All将停止执行并返回false第一次char.IsLetterOrDigit报告,false因为那时All无法履行合同。

Note!this answer do not strictly check alphanumerics (which typically is A-Z, a-z and 0-9). This answer allows local characters like ???.

笔记!这个答案没有严格检查字母数字(通常是 AZ、az 和 0-9)。这个答案允许像???.

Update 2018-01-29

更新 2018-01-29

The syntax above only works when you use a single method that has a single argument of the correct type (in this case char).

仅当您使用具有正确类型的单个参数(在本例中为char)的单个方法时,上述语法才有效。

To use multiple conditions, you need to write like this:

要使用多个条件,你需要这样写:

if (yourText.All(x => char.IsLetterOrDigit(x) || char.IsWhiteSpace(x)))
{
}

回答by goodeye

I needed to check for A-Z, a-z, 0-9; without a regex (even though the OP asks for regex).

我需要检查 AZ、az、0-9;没有正则表达式(即使 OP 要求使用正则表达式)。

Blending various answers and comments here, and discussion from https://stackoverflow.com/a/9975693/292060, this tests for letter or digit, avoiding other language letters, and avoiding other numbers such as fraction characters.

在这里混合各种答案和评论,以及来自https://stackoverflow.com/a/9975693/292060 的讨论,这会测试字母或数字,避免其他语言字母,并避免其他数字,如分数字符。

if (!String.IsNullOrEmpty(testString)
    && testString.All(c => Char.IsLetterOrDigit(c) && (c < 128)))
{
    // Alphanumeric.
}

回答by Thabiso Mofokeng

In order to check if the string is both a combination of letters and digits, you can re-write @jgauffin answer as follows using .NET 4.0 and LINQ:

为了检查字符串是否同时是字母和数字的组合,您可以使用 .NET 4.0 和 LINQ 如下重写@jgauffin 答案:

if(!string.IsNullOrWhiteSpace(yourText) && 
yourText.Any(char.IsLetter) && yourText.Any(char.IsDigit))
{
   // do something here
}

回答by Mahdi Al Aradi

I advise to not depend on ready made and built in code in .NET framework , try to bring up new solution ..this is what i do..

我建议不要依赖 .NET 框架中现成和内置的代码,尝试提出新的解决方案..这就是我所做的..

public  bool isAlphaNumeric(string N)
{
    bool YesNumeric = false;
    bool YesAlpha = false;
    bool BothStatus = false;


    for (int i = 0; i < N.Length; i++)
    {
        if (char.IsLetter(N[i]) )
            YesAlpha=true;

        if (char.IsNumber(N[i]))
            YesNumeric = true;
    }

    if (YesAlpha==true && YesNumeric==true)
    {
        BothStatus = true;
    }
    else
    {
        BothStatus = false;
    }
    return BothStatus;
}

回答by Alexa Adrian

Based on cletus's answer you may create new extension.

根据 cletus 的回答,您可以创建新的扩展。

public static class StringExtensions
{        
    public static bool IsAlphaNumeric(this string str)
    {
        if (string.IsNullOrEmpty(str))
            return false;

        Regex r = new Regex("^[a-zA-Z0-9]*$");
        return r.IsMatch(str);
    }
}

回答by Douglas Gaskell

Same answer as here.

此处相同的答案。

If you want a non-regex ASCII A-z 0-9check, you cannot use char.IsLetterOrDigit()as that includes other Unicode characters.

如果您想要非正则表达式 ASCIIA-z 0-9检查,则不能使用,char.IsLetterOrDigit()因为它包含其他 Unicode 字符。

What you can do is check the character code ranges.

您可以做的是检查字符代码范围。

  • 48 -> 57 are numerics
  • 65 -> 90 are capital letters
  • 97 -> 122 are lower case letters
  • 48 -> 57 是数字
  • 65 -> 90 是大写字母
  • 97 -> 122 是小写字母

The following is a bit more verbose, but it's for ease of understanding rather than for code golf.

下面的内容有点冗长,但它是为了便于理解而不是为了代码高尔夫。

    public static bool IsAsciiAlphaNumeric(this string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return false;
        }

        for (int i = 0; i < str.Length; i++)
        {
            if (str[i] < 48) // Numeric are 48 -> 57
            {
                return false;
            }

            if (str[i] > 57 && str[i] < 65) // Capitals are 65 -> 90
            {
                return false;
            }

            if (str[i] > 90 && str[i] < 97) // Lowers are 97 -> 122
            {
                return false;
            }

            if (str[i] > 122)
            {
                return false;
            }
        }

        return true;
    }