spiderplant0
spiderplant0

Reputation: 3952

How to use regular expression to extract bit in middle of a string

Using PHP PCRE regular expressions I want to extract the centre part of a string where the parts either side may or may not occur. I.e.

n bedroom property type in some town

I want to extract 'property type' using one regular expression. I do not know all the possibilities for property type but what is consistent is the start bit (its always '\d bedroom') and the end bit (its always 'in some town'). Also, either the start or end bits (or both) may not be present.

I.e. the subject strings could be one of ...

6 bedroom ground floor flat in Edinburgh

house in Manchester

3 bedroom apartment

So want to extract 'ground floor flat', 'house', and 'apartment' respectively.

Something like this (which doesn't quite work)....

(\s*\d+\s+bedrooms?\s*)?(.*?)(\s+in)?

Upvotes: 1

Views: 659

Answers (2)

Toto
Toto

Reputation: 91385

Add anchors to your regex and declare first ant last group to be not captured:

/^(?:\s*\d+\s+bedrooms?\s*)?(.*?)(?:\s+in\s.*)?$/

Upvotes: 4

3on
3on

Reputation: 6339

This #(((?<bedroomCount>\d+)\s+bedroom)\s+)?(?<type>.+?)\s(in\s+(?<city>\w+))?\n#i works I think but you need an extra newline ad the end of the testing string.

An example here

Upvotes: 1

Related Questions