0

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

3
  • So you are not interested in the word Owl, but rather O,w and l characters? Commented Jul 1, 2018 at 15:57
  • Yes, the individual characters Commented Jul 1, 2018 at 16:01
  • Do you need o, w and l to be matched in this order or in any order? Commented Jul 1, 2018 at 18:09

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.