使用C#和regex类搜索并提取包含文本文件中特定单词的句子 [英] search and extract sentence containg specific word in a text file using C# and regex class

查看:492
本文介绍了使用C#和regex类搜索并提取包含文本文件中特定单词的句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试阅读文本文件并从文件中提取包含特定单词的子句/句子。





I am trying to read a text file and extract a clause/ sentence containg specific words from the file .


using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern =@"(?<=^|\.)[^.]*?(? =\bshall incure to all bank of amrerica Affiliates\b).*(\.|$)"
      string input = "anita singh is good girl.Supplier expressly acknowledges and agrees that the rights and obligations of Bank of india set forth in this Agreement shall inure to all Bank of india Affiliates.anita is a good girl." ;
      Match match = Regex.Match(input, pattern);
      if (match.Success)
      {
         Console.WriteLine("Match: " + match.Value);
      } 
   }
}







输出将是< b / b




供应商明确承认并同意本协议中规定的印度银行的权利和义务应适用于所有印度银行的关联公司。




output would be


Supplier expressly acknowledges and agrees that the rights and obligations of Bank of India set forth in this Agreement shall inure to all Bank of india Affiliates.

推荐答案


string input = anita singh是好女孩。供应商明确承认并同意本协议中规定的印度银行的权利和义务适用于所有银行印度Affiliates.anita是一个好女孩。;
匹配匹配= Regex.Match(输入,模式);
如果(match.Success)
{
Console.WriteLine( 匹配: + match.Value);
}
}
}
)" string input = "anita singh is good girl.Supplier expressly acknowledges and agrees that the rights and obligations of Bank of india set forth in this Agreement shall inure to all Bank of india Affiliates.anita is a good girl." ; Match match = Regex.Match(input, pattern); if (match.Success) { Console.WriteLine("Match: " + match.Value); } } }







输出将是





供应商明确承认并同意权利和本协议中规定的印度银行的义务应适用于所有印度银行关联公司。




output would be


Supplier expressly acknowledges and agrees that the rights and obligations of Bank of India set forth in this Agreement shall inure to all Bank of india Affiliates.


我发现这是一种可能的解决方案。我知道从现在起我就会保留它。



I found this as a possible solution. I know I'm keeping it around from now on.

public static bool ExactMatch(string input, string match)
{
    return Regex.IsMatch(input, string.Format(@"\b{0}\b", Regex.Escape(match)));
}


让您的生活更轻松,首先将字符串拆分成句子。



示例:

Make your life easier and split the string into sentences first.

Example:
var regex = new Regex(@".*your text goes here.*");
var text = "This is a Test 2. This is the sentence with 'your text goes here' xyz. The middle sentence is the one we want.";

var texts = text.Split('.');
foreach(var t in texts) {
   if(regex.IsMatch(t)) {
      Console.WriteLine(t.Trim());
   }
}


这篇关于使用C#和regex类搜索并提取包含文本文件中特定单词的句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆