0

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

组词:“房子”、“时间”、“这就是”、“”、“

应该返回匹配的句子:

1)“我从房子里出来了”->匹配“房子的

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

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

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

更新:实现语言将使用 PHP

4

1 回答 1

2

描述

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

^.*?(?:\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
    )
于 2013-07-01T01:16:49.410 回答