3 回答
TA贡献1836条经验 获得超3个赞
这很容易实现。该string类型实现IEnumerable<char>,因此您可以使用 LINQAll方法检查其所有字符是否满足谓词。在您的情况下,谓词是每个字符都包含在allowedChars集合中,因此您可以使用以下Contains方法:
private static bool CheckInvalidInput(string stringToCheck, IEnumerable<char> allowedChars)
{
return stringToCheck.All(allowedChars.Contains);
}
如果您的allowedChars集合变大,您可能希望将其转换为 aHashSet<char>以获得更好的性能。
完整示例:
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
// var allowedChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };
var allowedChars = "0123456789.";
Console.WriteLine(CheckInvalidInput("54323.5", allowedChars)); // True
Console.WriteLine(CheckInvalidInput("543g23.5", allowedChars)); // False
}
private static bool CheckInvalidInput(string stringToCheck, IEnumerable<char> allowedChars)
{
return stringToCheck.All(allowedChars.Contains);
}
}
TA贡献1827条经验 获得超9个赞
这可以使用非常简单的模式来完成。Regex.IsMatch(yourString, @"^[\d.]+$");
^是行的开头
[\d.]+匹配一个或多个字符(或.或0-9)
$是行尾
编辑:这也将匹配.
如果此行为不是有意的,请尝试使用此^(?=\d)[\d.]+$
TA贡献1865条经验 获得超7个赞
如果允许的字符数组是动态的,您可以创建过程,该过程将接受允许的字符数组并动态构建模式。请注意,您必须转义某些字符才能在 Regex 中使用:
static void TestRegex(char[] check_chars)
{
string[] inputs = { "54323.5", "543g23.5" };
var check_chars2 = check_chars.Select(c => Regex.Escape(c.ToString()));
string pattern = "^(" + string.Join("|", check_chars2) + ")+$";
foreach (string input in inputs)
{
WriteLine($"Input {input} does{(Regex.IsMatch(input, pattern) ? "" : " not")} match");
}
}
// Output:
// Input 54323.5 does match
// Input 543g23.5 does not match
- 3 回答
- 0 关注
- 287 浏览
添加回答
举报
