C# 使用C中的正则表达式检查给定字符串中的单词#
我目前正在尝试检查用户输入的字符串中是否包含特定的单词。我使用的是正则表达式,代码如下:C# 使用C中的正则表达式检查给定字符串中的单词#,c#,regex,C#,Regex,我目前正在尝试检查用户输入的字符串中是否包含特定的单词。我使用的是正则表达式,代码如下: class Program { static void Main(string[] args) { string input = @"oaaawaala"; string word = "Owl"; string pattern = Regex.Replace(word, ".", ".*$0"); RegexOpti
class Program
{
static void Main(string[] args)
{
string input = @"oaaawaala";
string word = "Owl";
string pattern = Regex.Replace(word, ".", ".*$0");
RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;
var found = Regex.Matches(input, pattern, options).Count > 0;
Console.WriteLine("Found: {0}", found);
}
}
上述代码中的'found'值为true,因为根据'pattern'在输入'oaaawaala'中找到了单词'Owl'
但是,如果我将输入序列更改为“alaawaao”,或者输入以任何其他方式被置乱,“found”的值为false,因为模式不再匹配。我需要的解决方案是,应该在任何给定的字符串中找到“单词”——加扰或解读。关于如何进行的任何建议
谢谢为什么不检查
input
是否包含word
中的所有字符
class Program
{
static void Main(string[] args)
{
string input = @"oaaawaala";
string word = "Owl";
var found = word.ToCharArray().Select(c => char.ToUpper(c)).Distinct().All(c => input.ToUpper().Contains(c));
Console.WriteLine("Found: {0}", found);
}
}
对于正则表达式解决方案,请尝试以下操作:
string input = @"oaaawaala";
string word = "Owl";
if (Regex.IsMatch(input, Regex.Escape(word), RegexOptions.IgnoreCase))
{
MatchCollection matches = Regex.Matches(input, Regex.Escape(word), RegexOptions.IgnoreCase);
Console.WriteLine("Found: {0}", matches[0].Groups[0].Value);
}
因此,您对Owl这个词不感兴趣,而是对O、w和l字符感兴趣?是的,您需要的单个字符是
O
、w
和l
按此顺序还是按任何顺序匹配?