簡體   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