繁体   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