【问题标题】:Regular Expression for a specific set of words in a sentence句子中一组特定单词的正则表达式
【发布时间】:2013-07-01 00:22:38
【问题描述】:

在创建可以在句子中定位特定单词集的正则表达式方面,我需要一些帮助。在我们搜索句子之前,特定的单词或单词集是已知的。这些词将永远存在于句子中。随着时间的推移,该集合将扩大。下面的例子,

一组词:“of the house”、“time”、“this is how”、“coming", ""

应该返回匹配的句子:

1) “我要出来of the house” -> 匹配“of the house

2)“我记得我小时候的时间”->匹配“时间

3) “好吧,我不确定你做了什么,但是这就是我解决问题的方法”-> 匹配“这就是方法

4) “你什么时候回家回家?” -> 匹配“home

更新:实现语言将是 PHP

【问题讨论】:

  • 一个简单的组合"of the house|time|this is how|coming|home"应该可以工作,有什么问题?
  • 味道/工具是什么?
  • @acdcjunior 可能是 PHP,即 PCRE(由于 preg-match 标签)
  • 我很抱歉省略了语言。它将提交给 PHP API

标签: regex preg-match regex-negation regex-lookarounds regex-greedy


【解决方案1】:

说明

此表达式将匹配您的短语,并确保它们不会嵌入另一个更大的单词中。

^.*?(?:\s|^)(of\sthe\shouse|time|this\sis\show|home)(?=\W|$).*

PHP 代码示例:

你没有指定语言,所以我只是提供这个 php 示例来简单地展示它是如何工作的。

示例文本

1) "I was coming out of the house"
2) "I remember the time when I used to be a baby"
3) "Well, I am not sure what you did, but this is how I fix my problems"
4) "When are you coming home?"
5) "This is howard Timey said of the houseboat"
6) "The last word in this line is home

代码

<?php
$sourcestring="your source string";
preg_match_all('/^.*?(?:\s|^)(of\sthe\shouse|time|this\sis\show|home)(?=\W|$).*/imx',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

匹配项

[0] => Array
    (
        [0] => 1) "I was coming out of the house"
        [1] => 2) "I remember the time when I used to be a baby"
        [2] => 3) "Well, I am not sure what you did, but this is how I fix my problems"
        [3] => 4) "When are you coming home?"
        [4] => 6) "The last word in this line is home
    )

[1] => Array
    (
        [0] => of the house
        [1] => time
        [2] => this is how
        [3] => home
        [4] => home
    )

【讨论】:

  • [\W\s\r\n]\W 相同。此外,如果字符串以关键字结尾,这将不起作用。 (因为前瞻需要一个字符)我只是在两端使用一个单词边界。
  • 现在(?=\W|$) 在给定的情况下完全等同于(尽管效率低于)\b。但至少它现在有效。 +1
猜你喜欢
  • 2012-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-01
  • 2022-11-20
  • 2021-09-18
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多