检查字符串是否包含文件的关键字c#

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

我正在尝试检查字符串是否包含文本文件中存在的关键字,但什么也没做

如果您需要更多信息,请问我

例如我有一个像这样的 keywords.txt :

example1
example2
example3

我想看看这些关键字之一是否在 json 字符串中,如下所示:

{ 
     "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"
}

你可以在下面看到我的尝试 所以我希望你能帮我解决这个问题谢谢

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

如果你想检查文件中的任何单词是否包含在字符串中,首先你需要store all lines从文件到一个数组,然后你需要字符串是否包含数组中的任何字符串。

Enumerable.Any method

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

要做到这一点,请尝试以下操作,

var examples = File.ReadAllLines(@"keywords.txt");

if(examples.Any(x => json.Contains(x))
{
  //Your business logic
}
else
{
  //Your business logic
}

如果你想检查完全匹配,那么你可以尝试使用 RegEx IsMatch() 函数

喜欢,

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
}

下面的方法将有助于消除误报,它会检查特定的 关键字出现在 JSON 字符串中,然后才进一步处理

Just doing String.contains might swallow these false positives and come up as true

输入文件关键词

keyword  //This will return as false
keyword1 //This will return true 

输入文件Json

{ 
   "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":"keyword1"
}

主要

var keyWordFilePath = @"keyWord.txt";
var jsonFilePath = @"json.txt";
var jsonString = File.ReadAllText(jsonFilePath);
var keywords = File.ReadAllText(keyWordFilePath).Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

foreach (var key in keywords)
{

      //We are checking if json string contains key and also checking that it is only that definite key 
      var extractSpecificKey = jsonString.Substring(jsonString.IndexOf(key), key.Length+1);

      if (extractSpecificKey == key+ @"""")
      {

         Console.WriteLine($"Key {extractSpecificKey} present in json");

      }
     //False Positives
      else
      {
         Console.WriteLine($"Key {key} NOT present in json");
      }
}

Console.Read();

输出

Key keyword NOT present in json
Key keyword1" present in json