Search code examples
c#stringcontainskeyword

Check if a string contains the keywords of a file c#


I'm trying to check if a string contains a keyword present in a text file but nothing was done

If you need more information ask me

For exemple i have a keywords.txt like this :

example1
example2
example3

and i want to see if one of these keyword are in a json string like this :

{ 
     "title":"new doc 4",
     "rotate":0,
     "sort_key":"new doc 4",
     "tag_ids":"",
     "doc_id":"ee4DM4Ly7CFBM3JFWAW60TUX",
     "co_token":"",
     "p":"XQXLDEQyA2hf6BBfyXhSaUHL",
     "t":"1474932063",
     "c":"2",
     "updated":"1474932063"
}

You can see what i have try below So I'm hoping you can help me solve this problem thanks

if (json.Contains(File.ReadAllText(@"keywords.txt")))
{
    //My if logic
}
else
{
    //My else logic
}

Solution

  • If you want check any word in file contains in string then, first you need to store all lines from file into an Array, then you need to string contains any of string from array or not.

    Enumerable.Any method

    Determines whether any element of a sequence exists or satisfies a condition.

    To do that try below,

    var examples = File.ReadAllLines(@"keywords.txt");
    
    if(examples.Any(x => json.Contains(x))
    {
      //Your business logic
    }
    else
    {
      //Your business logic
    }
    

    If you want to check exact match then you can try with RegEx IsMatch() function

    like,

    using System.Text;
    using System.Text.RegularExpressions;
    ...
    var examples = File.ReadAllLines(@"keywords.txt");
    
    //If you want to ignore case then, pass third parameter to IsMatch() "RegexOptions.IgnoreCase"
    if(examples.Any(x => Regex.IsMatch(json, $@"\b{x}\b"))   
    {
      // here "\b" stands for boundary
      //Your business logic
    }
    else
    {
      //Your business logic
    }