如何验证字符串以只允许其中的字母数字字符?

如何使用正则表达式验证只允许字母数字字符的字符串?

(我也不想留出任何空间)。

250308 次浏览

使用以下短语:

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

即:

using System.Text.RegularExpressions;


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

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

使用 ^[a-zA-Z0-9]+$禁止下划线。

请注意,这两者都要求字符串不为空。使用 *而不是 +允许空字符串。

你可以很容易地用扩展函数而不是正则表达式..。

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

每条评论:) ..。

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


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

虽然我认为基于正则表达式的解决方案可能是我要采用的方式,但我还是倾向于将其封装为一种类型。

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

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

如果您关心的话,您可以更加喜欢并实现所有的相等运算符,或者从普通的 ol’string 显式转换为 AlphaNumericString。

在.NET 4.0中你可以使用 LINQ:

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

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

注意!这个答案不会严格检查字母数字(通常是 A-Z、 A-Z 和0-9)。这个答案允许使用像 åäö这样的本地字符。

更新2018-01-29

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

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

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

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

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

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

为了检查字符串是否同时是字母和数字的组合,您可以使用以下方法重写@jgaffin 回答。NET 4.0和 LINQ:

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

我建议不要依赖于现成的和内置的代码。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;
}

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

答案和 给你一样。

如果希望进行非正则表达式 ASCII A-z 0-9检查,则不能使用包含其他 Unicode 字符的 char.IsLetterOrDigit()

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

  • 48-> 57是数字
  • 65-> 90是大写字母
  • 97-> 122是小写字母

下面的内容有点冗长,但是这是为了便于理解,而不是为了编写代码。

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

虽然有很多方法可以去掉这只猫的皮肤,但我更喜欢将这些代码封装到可重用的扩展方法中,这样就可以轻松完成后续工作。在使用扩展方法时,还可以避免使用正则表达式,因为它比直接字符检查慢。我喜欢使用 Extensions.cs NuGet 包中的扩展。它使得这个检查简单如下:

  1. https://www.nuget.org/packages/Extensions.cs包添加到项目中。
  2. 将“ using Extensions;”添加到代码的顶部。
  3. "smith23".IsAlphaNumeric()将返回 True,而 "smith 23".IsAlphaNumeric(false)将返回 False。默认情况下,.IsAlphaNumeric()方法忽略空格,但是也可以如上所示重写它。如果希望允许使用这样的空格,即 "smith 23".IsAlphaNumeric()将返回 True,则只需默认设置参数。
  4. 其余代码中的每一个检查都是简单的 MyString.IsAlphaNumeric()

12年零7个月后,如果现在有人读到这篇文章。

编译后的 RegEx 实际上在.NET5和.NET6中具有最好的性能

请看下面的链接,其中我比较了几个不同的答案给出了这个问题。主要比较已编译的 RegEx、 For 循环和 Linq 谓词: https://dotnetfiddle.net/WOPQRT

备注: 如前所述,此方法只在.NET5和.NET6中更快。

NET Core 3.1及以下版本显示 RegEx 是最慢的。

不管是什么版本的.NET,For-Loop 方法总是比 Linq 谓词快。