Search code examples
phpregexsentence

Pattern matching a uniform sentence structure


I have a sentence with a uniform structure that I would like to use regex to pick out certain words from the sentence. For example the sentence structure is as follows:

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

where words in quotes are hard coded and words without quotes are variable. For example, based on that sentence structure, the following sentences are applicable:

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

I need help coming up with a regex pattern that would match against this and allow me to parse out the [train] and [stop]. My regex kunfu is weak, and I could use some help.


Solution

  • Very simple regexp: '^Take the (.*) bound train to (.*)\.$' that stores [train] in the first capture group and [stop] in the second.

    ^               # 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