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 si开发者_开发技巧de 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)?
Add anchors to your regex and declare first ant last group to be not captured:
/^(?:\s*\d+\s+bedrooms?\s*)?(.*?)(?:\s+in\s.*)?$/
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
精彩评论