开发者

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

开发者 https://www.devze.com 2023-04-08 10:49 出处:网络
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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号