Reputation: 3952
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
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