【问题标题】:Get a phrase between "." and that has a specific word在“.”之间找到一个短语并且有一个特定的词
【发布时间】:2019-06-12 00:07:22
【问题描述】:

假设我有以下文本:

“当我长大的时候,我们住在一间带完整地下室的小房子里。”妈妈用一块铺在水泥地板上的地毯和一张我们可以玩耍的沙发和椅子让地下室变得舒适。 ,那是我们存放大部分玩具和珍宝的地方。

我们在那些木楼梯上上下了很多次,过了一会儿,它们开始看起来很磨损和邋遢。妈妈决定她要画它们。那是在快干涂料开始使用之前的日子,涂料需要一整天才能干燥。 "

我需要一个开始和结束由“。”分隔的正则表达式。并且包含两个特定的词(例如 -> 地下室),结果将是:

“妈妈用铺在水泥地板上的地毯和可以玩耍的沙发和椅子让地下室变得舒适。”

【问题讨论】:

  • 您能否向我们提供您为此尝试的代码?您还需要向我们提供一个实际问题。
  • 稍微编辑一下就可以使这样的问题易于回答。一大段无差别的文字太难浏览了。
  • 这么多问题。您想在句子中间处理专有名词吗?引号呢?以感叹号或问号结尾的句子呢?如果句子是第一句并且前面没有句号怎么办?如果省略末尾的句号怎么办?如果有多个匹配项怎么办?如果“the”和“basement”之间的间距不一致怎么办?

标签: c# .net regex .net-core


【解决方案1】:

你可以使用这个正则表达式,

[A-Z][^.]*the basement[^.]*\.

说明:

[A-Z] - 此正则表达式以大写字母开头,因为句子以大写字母开头。

[^.]* - 然后它后面可以跟零个或多个除文字点以外的任何字符

the basement - 后面跟着你想要的文本。

[^.]* - 然后它后面可以跟零个或多个除文字点以外的任何字符

\. - 最后以文字点结束

Live Demo

【讨论】:

  • 句子开头的大写字母?一般来说,这可能行不通。如果句子中间有专有名词怎么办?
  • 虽然英语很难。 Let's meet at 8:00 a.m. in the basement.
【解决方案2】:

这是一个有点健壮的解决方案。它处理句点(即句号)但不处理“点”(例如“8:00 a.m.”或“e.g.”)。

void Main()
{
    var s = 

    @"When I was growing up, we lived in a little house with a full basement. Mom made the basement cozy with a rug covering the concrete floor and a couch and chair that we could play on. , and that was where we kept most of our toys and the things we treasured.

    We went up and down those wooden stairs many times, and after a while they began to look pretty scuffed and scruffy. Mom decided she was going to paint them. That was in the days before quick-drying paints came into use, and it would take a full day for the paint to dry.";

    Console.WriteLine(Foo(s, "the", "basement"));

}

IEnumerable<string> Foo(string s, params string[] words)
{
    var regexes = from w in words select new Regex(w, RegexOptions.IgnoreCase);

    var xs = new Stack<List<char>>();
    xs.Push(new List<char>());

    foreach (var c in s)
    {
        xs.Peek().Add(c);

        if(c == '.')
            xs.Push(new List<char>());
    }               

    var candidates = xs.Reverse().Select (x => new string(x.ToArray()) );

    foreach (var candidate in candidates)
        if(regexes.All(x => x.IsMatch(candidate)))
            yield return candidate;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-19
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多