我有一个字符串,我需要检查这个字符串是否包含任何不在给定列表中的字符。
假设我有这个允许的字符new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' , '.'}
如果字符串是"54323.5“-这将是ok!
如果字符串是"543g23.5“-这是不可以的,因为它包含的"g”不在我允许的字符列表中。
空字符串被视为无效。
我试图通过使用"IndexOfAny()“来实现这一点,但到目前为止还没有成功。当然,将所有不允许的字符传递给此方法不是一个好的解决方案。
请注意,允许的字符列表可能会发生变化,基于列表变化更改验证算法不被视为一种解决方案。
对于那些问我我尝试过的代码的人来说,这是:
private bool CheckInvalidInput(string stringToCheck)
{
char[] allowedChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
var chars = Enumerable.Range(0, char.MaxValue + 1)
.Select(i => (char)i)
.ToArray();
var unallowedChars = chars.Except(allowedChars).ToArray();
bool validString = true;
if(stringToCheck.IndexOfAny(unallowedChars) != -1)
{
validString = false;
}
return validString;
}
希望你能有一个更好的解决方案:D。
发布于 2018-12-19 05:27:11
这很容易实现。string
类型实现了IEnumerable<char>
,因此您可以使用LINQ All
方法来检查它的所有字符是否满足谓词。在您的示例中,谓词是每个字符都包含在allowedChars
集合中,因此您可以使用Contains
方法:
private static bool CheckInvalidInput(string stringToCheck, IEnumerable<char> allowedChars)
{
return stringToCheck.All(allowedChars.Contains);
}
如果您的allowedChars
集变得很大,您可能希望将其转换为HashSet<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);
}
}
发布于 2018-12-19 04:02:01
这可以使用一个非常简单的模式来完成。Regex.IsMatch(yourString, @"^[\d.]+$");
^
是该行的开头
[\d.]+
匹配一个或多个字符( .
或0-9
)
$
是行的末尾
编辑:这也将匹配.
如果此行为不是故意的,请尝试使用此^(?=\d)[\d.]+$
发布于 2018-12-19 05:02:13
如果允许的字符数组是动态的,则可以创建接受允许字符数组并动态构造模式的过程。请注意,您必须转义某些字符才能在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
https://stackoverflow.com/questions/53840169
复制相似问题