Reputation: 35
I'm currently attempting to check if a specific word is contained in a user-entered string. I'm using Regular Expressions and have the following code:
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);
}
}
The value of 'found' in the above code is true as the word 'Owl' is found in the input 'oaaawaala', based on the 'pattern'.
However, if I change the sequence of input to 'alaawaaao' or if the input is scrambled any other way, the value of 'found' is false since the pattern no longer matches. The Solution I need is that the 'word' should be found in any given string - scrambled or unscrambled. Any suggestions on how to go about this.
Thanks
Upvotes: 0
Views: 124
Reputation: 102
For regex solution, try this:
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);
}
Upvotes: 0
Reputation: 2611
Why not just check that input
contains all characters from 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);
}
}
Upvotes: 1