繁体   English   中英

模式匹配统一的句子结构

[英]Pattern matching a uniform sentence structure

我有一个结构统一的句子,我想使用正则表达式从句子中挑选出某些单词。 例如句子结构如下:

["Take the"] + [train] + ["bound train to"] + [stop]

其中引号中的单词是硬编码的,没有引号的单词是可变的。 例如,基于该句子结构,以下句子是适用的:

- Take the L bound train to 1st street.
- Take the 1 bound train to neverland. 

我需要帮助想出一个与此匹配的正则表达式模式,并允许我解析出 [train] 和 [stop]。 我的正则表达式功夫很弱,我可以使用一些帮助。

非常简单的正则表达式: '^Take the (.*) bound train to (.*)\\.$'[train]存储在第一个捕获组中,将[stop]在第二个捕获组中。

^               # Match the start of the string
Take the        # Match the literal string
(.*)            # Capture the [train]
bound train to  # Match the literal string
(.*)            # Capture the [stop]
\.              # Match the fullstop 
$               # Match the end of string
preg_match("/^Take\sthe\s([\d\w]+)\sbound\strain\sto\s([\w\d]+)$/", $string, $hits);

这样的事情应该工作

根据我的理解,您似乎想做某种模板,这需要重新设计句子结构和格式。

我看到以下内容:

Take the %start% bound train to %stop%

这很容易用您需要的特定单词替换。

/%stop%/Union Station
/%stop%/East Station

我知道这解决了您的问题,但它会提供比捕获所有正则表达式更好的解决方案,因为将来会/可能会变得难以维护。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM