如何检查字符串是否只包含数组中的单词?
如果字符串使用true
在数组中包含任何单词,则可以返回Contains()
。
public bool ValidateString(string strCondition)
{
List<string> words = new List<string>() { "true", "false", "&&", "||", " " };
foreach (string word in words)
{
if(strCondition.Contains(word))
return true;
}
return false;
}
但是,如果作为参数发送的字符串( false
)包含除true
、false
、&&
、||
以外的任何单词、字母表或数字等,如何返回?在Regex
中是否有任何选择,或者某个人能想出一个好的解决方案?
编辑
以下内容应返回true
true && false || false && false
true || false && false && false
下面应该返回false,因为它包含了true
、false
、&&
、||
以外的单词/数字/特殊字符,
true & false || false < false
true >> false && false && false
true and false 123 false && false
true || false && false xyz false
发布于 2015-03-24 07:05:23
首先,您的代码受到了clbuttic问题的影响:它将返回包含单词“不真实”的字符串的true
,因为代码不注意单词边界。
如果要检查是否包含其他单词,请拆分字符串,并根据“已批准”单词列表检查每个项:
var allApproved = strCondition.Split(' ').All(word => words.Contains(word));
这种方法意味着words
中的单词不包含空格。
请注意,这并不是最有效的方法,尽管对于一个小列表来说,它可以很好地工作。如果列表很长,则改用HashSet<string>
。
发布于 2015-03-24 07:11:23
你可以这样做:
var regex = new Regex(@"(^(true|false|&&|\|\|)$)");
return regex.IsMatch(input);
发布于 2015-03-24 07:34:17
这是另一个答案,这似乎是你最初问的问题。如果我做对了,您想知道是否只有子字符串在List<string>
中的文本中。
因此,“不真实”将返回false
,因为"un“不在允许的”单词“列表中(更好的子字符串)。但“真实”是被允许的。
然后看看这个看起来更麻烦的方法,但是它需要检查一些与接受的答案不同的内容:
List<string> words = new List<string>() { "false", "true", "||", "&&", " " };
public bool ValidateString(string strCondition)
{
if(string.IsNullOrWhiteSpace(strCondition)) return true;
int charIndex = 0;
while (charIndex < strCondition.Length)
{
string wordFound = null;
foreach (string word in words)
{
if (word.Length + charIndex > strCondition.Length)
continue;
string substring = strCondition.Substring(charIndex, word.Length);
if (word == substring)
{
wordFound = word;
break;
}
}
if (wordFound == null)
return false;
else if (charIndex + wordFound.Length == strCondition.Length)
return true;
else
charIndex += wordFound.Length;
}
return false;
}
注意,我已经重新排序了列表,最长的字符串应该放在第一位,因为在上面的算法中,这是更有效的。
两个例子说明了它的作用:
bool check = ValidateString("truefalse||truetrue"); // true
bool check = ValidateString("truefals||etruetrue"); // false
https://stackoverflow.com/questions/29235926
复制