简体   繁体   English

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

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

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). (我也不想允许有任何空格)。

In .NET 4.0 you can use LINQ:在 .NET 4.0 中,您可以使用 LINQ:

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

yourText.All will stop execute and return false the first time char.IsLetterOrDigit reports false since the contract of All cannot be fulfilled then. yourText.All将停止执行并在第一次char.IsLetterOrDigit报告false时返回false ,因为此时All的合同无法履行。

Note!笔记! this answer do not strictly check alphanumerics (which typically is AZ, az and 0-9).这个答案没有严格检查字母数字(通常是 AZ、az 和 0-9)。 This answer allows local characters like åäö .这个答案允许像åäö这样的本地字符。

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

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)) {
  ...
}

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

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).现在,当你需要一个经过验证的字符串时,你可以让方法签名需要一个 AlphaNumericString,并且知道如果你得到一个,它是有效的(除了空值)。 If someone attempts to pass in a non-validated string, it will generate a compiler error.如果有人试图传入未经验证的字符串,则会生成编译器错误。

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。

I needed to check for AZ, az, 0-9;我需要检查 AZ、az、0-9; without a regex (even though the OP asks for regex).没有正则表达式(即使 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.
}

^\\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.使用*而不是+允许空字符串。

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
}

Same answer as here .此处相同的答案。

If you want a non-regex ASCII Az 0-9 check, you cannot use char.IsLetterOrDigit() as that includes other Unicode characters.如果您想要非正则表达式 ASCII Az 0-9检查,则不能使用char.IsLetterOrDigit()因为它包含其他 Unicode 字符。

What you can do is check the character code ranges.您可以做的是检查字符代码范围。

  • 48 -> 57 are numerics 48 -> 57 是数字
  • 65 -> 90 are capital letters 65 -> 90 是大写字母
  • 97 -> 122 are lower case letters 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;
    }

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

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward.虽然有很多方法可以给这只猫剥皮,但我更喜欢将这些代码包装到可重用的扩展方法中,这样以后的工作就变得微不足道了。 When using extension methods, you can also avoid RegEx as it is slower than a direct character check.使用扩展方法时,您还可以避免使用 RegEx,因为它比直接字符检查慢。 I like using the extensions in the Extensions.cs NuGet package.我喜欢使用 Extensions.cs NuGet 包中的扩展。 It makes this check as simple as:它使这项检查变得如此简单:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.https://www.nuget.org/packages/Extensions.cs包添加到您的项目中。
  2. Add " using Extensions; " to the top of your code.将“ using Extensions; ”添加到代码的顶部。
  3. "smith23".IsAlphaNumeric() will return True whereas "smith 23".IsAlphaNumeric(false) will return False. "smith23".IsAlphaNumeric()将返回 True 而"smith 23".IsAlphaNumeric(false)将返回 False。 By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden as shown above.默认情况下, .IsAlphaNumeric()方法会忽略空格,但它也可以被覆盖,如上所示。 If you want to allow spaces such that "smith 23".IsAlphaNumeric() will return True, simple default the arg.如果你想允许空格,这样"smith 23".IsAlphaNumeric()将返回 True,简单默认 arg。
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric() .其余代码中的所有其他检查都只是MyString.IsAlphaNumeric()

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

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

相关问题 我如何验证按键上的文本框以仅允许 blazor 服务器中的字母数字字符 - How can i validate textbox on keypress to allow only alphanumeric characters in blazor server 如何验证字符串仅允许包含数字的字符串或仅包含数字的字符串? - How can I validate a string to only allow string or string with numbers but not numbers only? 如何使用正则表达式从输入字符串中提取所有非字母数字字符? - How can I extract all non-alphanumeric characters from an input string using Regular Expressions? 如何验证字符串仅包含某些字符 - How to validate that a string contains only certain characters 在文本框中仅允许使用字母数字 - Allow only alphanumeric in textbox 如何验证TextBox仅允许数字。 - How do I validate an TextBox to only allow numbers. 如何解析字符串以生成特定的字母数字格式 - How can I parse string to produce specific alphanumeric format 我怎样才能使一个正则表达式应只允许2个字符M或F - How can i make a Regex such that is should allow only 2 characters M or F 仅从字符串的开头和结尾删除非字母数字字符 - Remove non-alphanumeric characters from start and end of string only 什么是只计算字符串数组中的字母数字字符的更有效方法? - What is a more efficient way to only count alphanumeric characters in an array of String?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM