簡體   English   中英

檢查字符串是否包含文件 c# 的關鍵字

[英]Check if a string contains the keywords of a file c#

我正在嘗試檢查字符串是否包含文本文件中存在的關鍵字,但什么也沒做

如果您需要更多信息,請詢問我

例如,我有一個這樣的關鍵字.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
}

下面的方法將有助於消除誤報,它檢查特定關鍵字是否存在於 JSON 字符串中,然后才進一步處理

只是做String.contains可能會吞下這些誤報並成為真的

輸入文件關鍵字

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

如果你想檢查文件中包含在字符串中的任何單詞,首先你需要將文件中的所有行存儲到一個數組中,然后你需要字符串是否包含數組中的任何字符串。

Enumerable.Any 方法

確定序列的任何元素是否存在或滿足條件。

要做到這一點,請嘗試以下,

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM