0

我想創建一個正則表達式,可以在一個句子中找到一組特定的單詞。在我們搜索句子之前,已知一組特定的單詞或單詞。這些詞將永遠存在於句子中。隨着時間的推移,該集合將會不斷擴大。下面的例子,正則表達式在一個句子中的一組單詞

組詞: 「房子的」, 「時間」, 「這是怎麼」, 「」, 「

句子應該返回匹配:

1)「我走出房子」 - >匹配的「家

2)「我記得時間時,我曾經是一個孩子」 - >匹配的「時間

3)「好了,我不知道你做了什麼,但這是我解決我的問題呢?」 - >匹配的‘這是怎麼

4)‘你什麼時候回家’ - >匹配爲「

UPDATE:實現的語言將會在PHP

+2

房子的簡單組合'「|添e |這是應該如何工作,這是什麼問題? – dasblinkenlight

+0

什麼是風味/工具? – acdcjunior

+0

@acdcjunior可能是PHP,即PCRE(由於'preg-match'標籤) –

回答

2

說明

這個表達式將匹配您的詞組,並保證它們不會嵌入到另一個更大的詞。

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

enter image description here

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 
    ) 
+1

''\ W \ s \ r \ n]與'\ W'相同。而且,如果字符串以關鍵字結尾,這將不起作用。 (因爲lookahead需要一個字符),我只是在兩端使用一個字邊界。 –

+0

不錯的電話,我已經更新了表達和示例文本。 –

+0

現在'(?= \ W | $)'在給定的情況下完全等價於(雖然效率低於)'\ b'。但至少現在起作用了。 +1 –

相關問題